package App.Repository;

import App.Model.Account.CrmUser;
import App.Model.BaseEnum;
import App.Model.Chat.ChatStage;
import App.Model.Chat.CrmChatGroup;
import App.Model.Chat.CrmChatGroupPart;
import App.Model.Chat.CrmChatStage;
import App.Model.CommonConstant;
import App.Model.Export.*;
import App.Model.Friend.CrmUserPart;
import App.Model.PageSummary;
import App.Model.Project.*;
import App.Model.Task.CrmTaskFile;
import App.Model.Task.CrmTaskMember;
import App.Model.Task.GetTaskPageItemsRequest;
import App.Repository.impl.CrmProjectStageDao;
import App.Service.TecentIMService;
import App.Utility.DateUtil;
import App.Utility.RandomColorGenerator;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
//import sun.util.resources.cldr.te.CurrencyNames_te;

/**
 * Created by xw on 2018/11/20.
 */

@Repository
public class ProjectRepository extends BaseRepository {

    @Resource
    TecentIMService _imService;

    @Autowired
    CommonRepository _commonRepository;

    @Autowired
    private CrmProjectStageDao crmProjectStageDao;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //新增
    @Transactional
    public Map<String, Object> insertProject(ProjectSaveRequest _request, List<String> _groupids, int userId, Map<String, List<String>> map) throws Exception {
        Map<String, Object> map1 = new HashMap<>();
        EntityManager _entityManager = getEntityManager();
        List<String> clientIds = new ArrayList<>();
        List<String> memberIds = new ArrayList<>();


        int result = 0;
        try {
            //群组加颜色标记
            String color= RandomColorGenerator.getRandomRGB16();
            //添加项目主数据
            String _projectid = UUID.randomUUID().toString();
            map1.put("id", _projectid);
            String _projectName = _request.getName();
            int _projectType = _request.getProjecttype();
            result = insertProject(_projectid, _projectName, _projectType, userId);

            List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);
            List<CrmProjectBasicFolder> _basicFolder = getProjectBasicFolder(_projectType);

            int _commonStageFolderType = BaseEnum.ProjectFolderType.Common.getProjectFolderType();
            List<CrmProjectBasicFolder> _commonStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _commonStageFolderType).collect(Collectors.toList());

            //服务端产生的folders
            List<ProjectFolderResponse> _serviceProjectFolders = new ArrayList<>();


            //添加项目文件夹
            String _realFolderName = "";
            String _projectFolderId = UUID.randomUUID().toString();

            for (CrmProjectBasicFolder _folder : _commonStageFolders) {
                _realFolderName = _folder.getRecname();
                int _innerFolderType = _folder.getInnerfoldertype();
                boolean _isLawyerFolder = false;
                insertProjectFolderBasic(_projectid, 0, _projectFolderId, _realFolderName, _commonStageFolderType, "", "", _innerFolderType, _isLawyerFolder, userId);

                //把生成的文件夹，放进文件夹池子
                ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                _theServiceFolder.setClientid("");
                _theServiceFolder.setFolderid(_projectFolderId);
                _theServiceFolder.setFoldername(_realFolderName);
                _theServiceFolder.setPartanme(_realFolderName);

                _theServiceFolder.setFoldertype(_folder.getRectype());
                _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                _theServiceFolder.setLawyerfolder(false);
                _serviceProjectFolders.add(_theServiceFolder);
            }

            List<ProjectStage> _stages = _request.getStages();
            for (ProjectStage _stage : _stages) {
                if (_stage.getStageid() == 0) {
                    if (!StringUtils.isEmpty(_stage.getStageName())) {
                        ProjectStageSaveRequest projectStageSaveRequest = new ProjectStageSaveRequest();
                        projectStageSaveRequest.setProjecttype(_projectType);
                        projectStageSaveRequest.setStagename(_stage.getStageName());
                        ProjectSaveStageResponse projectSaveStageResponse = saveProjectStage(projectStageSaveRequest, userId);
                        _stageNameList = getProjectStageName(_projectType);
                        _stage.setStageid(projectSaveStageResponse.getStageid());
                        _stage.setStageorder(projectSaveStageResponse.getOrder());
                    }

                }

                int _stageid = _stage.getStageid();
                List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                String _currentStageName = _currentSageNameList.get(0).getStagename();
                String _folderStageName = "(" + _currentStageName + ")";
                _folderStageName = "";

                //虚拟文件夹
                List<ProjectFolderResponse> _folders = _stage.getFolders();

                //服务端产生的阶段
                List<ProjectFolderResponse> _serviceStageFolders = new ArrayList<>();

                //保存项目的阶段
                insertProjectStageRelate(_projectid, _stageid, _stage.getStageorder(), userId);

                //委托人文件夹
                int _clientStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
                List<CrmProjectBasicFolder> _clientStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _clientStageFolderType).collect(Collectors.toList());

                //创建分组
                int _chatType = BaseEnum.ChatType.Project.getChatType();
                int _addGroupResult = 0;


                //添加阶段文件夹
                int _theStageFolderType = BaseEnum.ProjectFolderType.Stage.getProjectFolderType();
                List<CrmProjectBasicFolder> _theStageBaseFolders = _basicFolder.stream().filter(x -> x.getRectype() == _theStageFolderType).collect(Collectors.toList());
                for (CrmProjectBasicFolder _folder : _theStageBaseFolders) {

                    String _theFolderRecid = UUID.randomUUID().toString();
                    String _theFolderName = _folderStageName + _folder.getRecname();
                    int _stageFolderType = _folder.getRectype();
                    int _innerfoldertype = _folder.getInnerfoldertype();
                    String _theClientId = "";
                    boolean _isLawyerFolder = false;
                    String _prefixname = "";
                    if (_folder.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolder.getDefaultFolderType()) {
                        _isLawyerFolder = true;
                        _prefixname = "律师协作团队";
                    }

                    if (_folder.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolderWithOutPrefix.getDefaultFolderType()) {
                        _isLawyerFolder = true;
                        _prefixname = "";
                    }


                    insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _theFolderName, _theStageFolderType, "", _prefixname, _innerfoldertype, _isLawyerFolder, userId);

                    //生成委托人文件夹
                    ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                    _theServiceFolder.setClientid(_theClientId);
                    _theServiceFolder.setFolderid(_theFolderRecid);
                    _theServiceFolder.setFoldername(_theFolderName);
                    _theServiceFolder.setPartanme(_theFolderName);
                    _theServiceFolder.setFoldertype(_stageFolderType);
                    _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                    _theServiceFolder.setLawyerfolder(_isLawyerFolder);
                    _serviceStageFolders.add(_theServiceFolder);

                }

                //添加 委托人
                List<ProjectClientGroup> _clientGroups = new ArrayList<>();
                List<ProjectClient> _clients = _stage.getInfo().getClient();
                int _personType = BaseEnum.PersonType.Client.getPersonType();

                List<ProjectClientFolder> _clientTmp = new ArrayList<>();


                //get special folder
                String _newFolderName = "";
                List<CrmPorjectFolderSpecial> _folderSpecials = getProjectFolderSpecial(_projectType, _stageid);
                if (_folderSpecials != null && _folderSpecials.size() > 0) {
                    CrmPorjectFolderSpecial _special = _folderSpecials.get(0);
                    _newFolderName = _special.getShowname();
                }

                for (ProjectClient _client : _clients) {
                    String _clientRecid = UUID.randomUUID().toString();
                    String _clientName = _client.getName();
                    insertProjectClientSingle(_projectid, _stageid, _personType, _clientRecid, _client);

                    ProjectClientFolder _tmpInfo = new ProjectClientFolder();
                    _tmpInfo.setClientid(_client.getClientid());
                    _tmpInfo.setRecid(_clientRecid);
                    _tmpInfo.setClientname(_clientName);
                    _clientTmp.add(_tmpInfo);


                    //添加委托人团队的委托人组的文件夹
                    for (CrmProjectBasicFolder _folder : _clientStageFolders) {

                        String _theStagePartFolderName = "";
                        if (_folder.getIsReplaceable() && !_newFolderName.isEmpty()) {
                            _theStagePartFolderName = "正式提交给" + _newFolderName + "的材料";
                            _realFolderName = _folderStageName + _theStagePartFolderName;
                        } else {
                            _realFolderName = _folderStageName + _folder.getRecname();
                        }

                        int _innerFolderType = _folder.getInnerfoldertype();
                        boolean _isLawyerFolder = false;
                        String _theFolderRecid = UUID.randomUUID().toString();
                        insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _realFolderName, _clientStageFolderType, _clientRecid, _clientName, _innerFolderType, _isLawyerFolder, userId);

                        //生成委托人文件夹
                        ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                        _theServiceFolder.setClientid(_client.getClientid());
                        _theServiceFolder.setFolderid(_theFolderRecid);


                        _theServiceFolder.setFoldername(_clientName + _folderStageName + _theStagePartFolderName);
                        _theServiceFolder.setPartanme(_clientName + _folderStageName + _theStagePartFolderName);
                        _theServiceFolder.setFoldertype(_folder.getRectype());
                        _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                        _theServiceFolder.setLawyerfolder(false);
                        _serviceStageFolders.add(_theServiceFolder);
                    }


                    boolean _createIMGroupResult = false;
                    String _clientGroupid = UUID.randomUUID().toString();

                    //im group name 最长30字节
                    String _groupName = "委托人协作团队";
                    String _groupIntroduction = "[" + _currentStageName + "]" + _projectName + "_委托人协作团队";
                    String _imGroupName = "委托人协作团队";


                    String _rawIMGroupName = "[" + _currentStageName + "]" + _projectName;
                    _rawIMGroupName = "委协-" + _projectName;
                    _groupIntroduction = _rawIMGroupName;
                    if (_rawIMGroupName.length() > 10) {
                        _imGroupName = _rawIMGroupName.substring(0, 10);
                    } else {
                        _imGroupName = _rawIMGroupName;
                    }

                    if (_groupIntroduction.length() > 100) {
                        _groupIntroduction = _groupIntroduction.substring(0, 100);
                    }

                    int _clientGroupType = BaseEnum.ChatGroupType.Client.getChatGroupType();
                    _addGroupResult = insertChatGroup(_clientGroupid, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _clientRecid, _client.getName(), userId,color);
                    if (_addGroupResult > 0) {
                        _createIMGroupResult = _imService.createIMGroup(_clientGroupid, _imGroupName, _groupIntroduction, userId);
                    }

                    if (_createIMGroupResult) {
                        //System.out.println("create im group ok 1");
                        _groupids.add(_clientGroupid);
                        clientIds.add(_clientGroupid);
                    }

                    //添加委托人对应的成员
                    List<ProjectMember> _clientMembers = _client.getMembers();
                    if (_clientMembers != null && _clientMembers.size() > 0) {
                        insertProjectMemberBatch(_projectid, _stageid, _clientGroupid, _clientMembers, _clientRecid, userId);

                        //添加IM member
                        List<Integer> _tmpMemberIds = new ArrayList<>();
                        for (ProjectMember _m : _clientMembers) {
                            _tmpMemberIds.add(_m.getUserid());
                        }
                        //添加成员到im group
                        //List<Integer> _lawyerGroupMember = _members.stream().map(x -> x.getUserid()).distinct().collect(Collectors.toList());
                        _imService.addIMGroupMember(_clientGroupid, _tmpMemberIds, userId);
                    }

                    //为添加成员做准备
                    ProjectClientGroup _cg = new ProjectClientGroup();
                    _cg.setRecid(_clientRecid);
                    _cg.setClientid(_client.getClientid());
                    _cg.setGroupid(_clientGroupid);
                    _clientGroups.add(_cg);
                }


                //添加 对方当事人
                _personType = BaseEnum.PersonType.litigant.getPersonType();
                List<ProjectClient> _litigants = _stage.getInfo().getLitigant();
                int _ligigantStageFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();
                List<CrmProjectBasicFolder> _ligigantStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _ligigantStageFolderType).collect(Collectors.toList());

                for (ProjectClient _client : _litigants) {

                    String _clientRecid = UUID.randomUUID().toString();
                    insertProjectClientSingle(_projectid, _stageid, _personType, _clientRecid, _client);

                    ProjectClientFolder _tmpInfo = new ProjectClientFolder();
                    _tmpInfo.setClientid(_client.getClientid());
                    _tmpInfo.setRecid(_clientRecid);
                    _tmpInfo.setClientname(_client.getName());
                    _clientTmp.add(_tmpInfo);

                    //添加对方当事人文件夹
                    for (CrmProjectBasicFolder _folder : _ligigantStageFolders) {

                        String _theStagePartFolderName = "";
                        if (_folder.getIsReplaceable() && !_newFolderName.isEmpty()) {
                            _theStagePartFolderName = "正式提交给" + _newFolderName + "的材料";
                            _realFolderName = _folderStageName + _theStagePartFolderName;
                        } else {
                            _realFolderName = _folderStageName + _folder.getRecname();
                        }

                        int _innerFolderType = _folder.getInnerfoldertype();
                        boolean _isLawyerFolder = false;
                        String _theFolderRecid = UUID.randomUUID().toString();
                        insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _realFolderName, _ligigantStageFolderType, _clientRecid, _client.getName(), _innerFolderType, _isLawyerFolder, userId);

                        //生成委托人文件夹
                        ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                        _theServiceFolder.setClientid(_client.getClientid());
                        _theServiceFolder.setFolderid(_theFolderRecid);
                        _theServiceFolder.setFoldername(_realFolderName);
                        _theServiceFolder.setPartanme(_realFolderName);
                        _theServiceFolder.setFoldertype(_folder.getRectype());
                        _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                        _theServiceFolder.setLawyerfolder(false);
                        _serviceStageFolders.add(_theServiceFolder);
                    }
                }

                //添加项目基础数据
                insertProjectInfo(_projectid, _stageid, _stage);

                //添加备注
                List<ProjectRemark> _remarks = _stage.getInfo().getRemarks();
                if (_remarks != null) {
                    for (ProjectRemark _remark : _remarks) {

                        String _recid = UUID.randomUUID().toString();
                        insertProjectRemark(_projectid, _stageid, _recid, _remark.getContent(), userId);

                        //添加可以看到备注的人
                        List<ProjectInfoRemarkViewer> _viewers = _remark.getViewer();
                        insertProjectRemarkViewers(_projectid, _stageid, _recid, _viewers, userId);
                    }
                }

                //合议庭张三
                int _contactType = BaseEnum.ContactType.FullCount.getContactType();
                List<ProjectContact> _fullCount = _stage.getInfo().getFullcourt();
                insertProjectContact(_projectid, _stageid, _contactType, _fullCount, userId);

                //书记员王五
                _contactType = BaseEnum.ContactType.Clerk.getContactType();
                List<ProjectContact> _clerks = _stage.getInfo().getClerk();
                insertProjectContact(_projectid, _stageid, _contactType, _clerks, userId);


                //把自定义文件夹，保存到数据库
                //直接使用客户端传来的folderid
                // todo:需要使用来自客户端的clientid么
                int _userDefineFolderType = BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType();
                List<ProjectFolderResponse> _userDefinefolders = _folders.stream().filter(x -> x.getFoldertype() == _userDefineFolderType).collect(Collectors.toList());
                if (_userDefinefolders != null && _userDefinefolders.size() > 0) {
                    for (ProjectFolderResponse _folder : _userDefinefolders) {
                        String _theFolderRecid = _folder.getFolderid();
                        String _theRealFolderName = _folder.getFoldername();
                        int _innerFolderType = _folder.getInnerfoldertype();
                        boolean _isLawyerFolder = !_folder.isLawyerfolder();
                        String _prefixName = "";
                        String _relatedId = "";

                        _innerFolderType = getNextInnerFolderType(_projectid);
                        insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _theRealFolderName, _userDefineFolderType, _relatedId, _prefixName, _innerFolderType, _isLawyerFolder, userId);
                    }
                }

                //根据文件夹，编辑，然后写文件入数据
                List<ProjectFileFolder> _fileFolders = _stage.getFiles();
                if (_fileFolders != null && _fileFolders.size() > 0) {
                    for (ProjectFileFolder _folder : _fileFolders) {
                        int _theFolderType = _folder.getFoldertype();
                        if (_theFolderType == _commonStageFolderType) {

                            //从服务端文件夹中找到对应的文件夹
                            String _theFolerid = "";
                            Optional<ProjectFolderResponse> _theServiceFolder = _serviceProjectFolders.stream().filter(x -> x.getFoldertype() == _folder.getFoldertype()
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                            if (_theServiceFolder.isPresent()) {
                                ProjectFolderResponse _serviceFolder = _theServiceFolder.get();
                                _theFolerid = _serviceFolder.getFolderid();
                            }

                            List<ProjectFile> _theFiles = _folder.getItems();
                            if (_theFiles != null && _theFiles.size() > 0) {
                                for (ProjectFile _f : _theFiles) {
                                    String _fileRecid = UUID.randomUUID().toString();
                                    _f.setFolderid(_theFolerid);
                                    //把文件写入数据库
                                    insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                                }
                            }
                        } else if (_theFolderType == _theStageFolderType) {

                            //从服务端文件夹中找到对应的文件夹
                            String _theFolerid = "";
                            Optional<ProjectFolderResponse> _theServiceFolder = _serviceStageFolders.stream().filter(x -> x.getFoldertype() == _folder.getFoldertype()
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                            if (_theServiceFolder.isPresent()) {
                                ProjectFolderResponse _serviceFolder = _theServiceFolder.get();
                                _theFolerid = _serviceFolder.getFolderid();
                            }

                            List<ProjectFile> _theFiles = _folder.getItems();
                            if (_theFiles != null && _theFiles.size() > 0) {
                                for (ProjectFile _f : _theFiles) {
                                    String _fileRecid = UUID.randomUUID().toString();
                                    _f.setFolderid(_theFolerid);
                                    //把文件写入数据库
                                    insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                                }
                            }

                        } else if (_theFolderType == _userDefineFolderType) {

                            //把文件写入数据库
                            List<ProjectFile> _theFiles = _folder.getItems();
                            if (_theFiles != null && _theFiles.size() > 0) {
                                for (ProjectFile _f : _theFiles) {
                                    String _fileRecid = UUID.randomUUID().toString();
                                    _f.setFolderid(_folder.getFolderid());
                                    insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                                }
                            }

                        } else {

                            //找到文件夹对应的委托人或者对方当事人
                            //  Optional<ProjectFolderResponse> _requestFolder = _folders.stream().filter(x -> x.getFolderid().equals(_folder.getFolderid())).findFirst();
                            //  if (_requestFolder.isPresent()) {
                            //  ProjectFolderResponse _theRequestFolder = _requestFolder.get();
                            //  String _theClientId = _theRequestFolder.getClientid();

                            //找到服务端对应的文件夹
                            String _theFolerid = "";
                            String _theClientId = _folder.getClientid();
                            Optional<ProjectFolderResponse> _theServiceFolder = _serviceStageFolders.stream().filter(x -> x.getClientid().equals(_theClientId)
                                    && x.getFoldertype() == _folder.getFoldertype()
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                            if (_theServiceFolder.isPresent()) {
                                ProjectFolderResponse _serviceFolder = _theServiceFolder.get();
                                _theFolerid = _serviceFolder.getFolderid();
                            }

                            //把文件写入数据库
                            List<ProjectFile> _theFiles = _folder.getItems();
                            if (_theFiles != null && _theFiles.size() > 0) {
                                for (ProjectFile _f : _theFiles) {
                                    String _fileRecid = UUID.randomUUID().toString();
                                    _f.setFolderid(_theFolerid);
                                    insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                                }
                            }
                            // }
                        }
                    }
                }


                //添加项目任务
                List<ProjectTask> _tasks = _stage.getTasks();
                if (_tasks != null) {
                    insertProjectTasks(_projectid, _stageid, _tasks, userId);
                }

                //添加律师协作团队聊天组
                boolean _createIMGroupResult = false;
                int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
                String _clientGroupid = UUID.randomUUID().toString();

                _addGroupResult = 0;
                String _lawyerGroupid = UUID.randomUUID().toString();
                //String _groupName = _projectName + "律师协作团队";
                String _groupName = "律师协作团队";
                String _imGroupIntroduction = "[" + _currentStageName + "]" + _projectName + "_律师协作团队";
                String _imGroupName = "律师协作团队";

                String _rawIMGroupName = "律协-" + _projectName;
                _imGroupIntroduction = _rawIMGroupName;
                if (_rawIMGroupName.length() > 10) {
                    _imGroupName = _rawIMGroupName.substring(0, 10);
                } else {
                    _imGroupName = _rawIMGroupName;
                }

                if (_imGroupIntroduction.length() > 100) {
                    _imGroupIntroduction = _imGroupIntroduction.substring(0, 100);
                }


                int _lawyerGroupType = BaseEnum.ChatGroupType.Lawyer.getChatGroupType();
                _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, _projectid, _stageid, _chatType, _lawyerGroupType, "", "", userId,color);
                if (_addGroupResult > 0) {
                    _createIMGroupResult = _imService.createIMGroup(_lawyerGroupid, _imGroupName, _imGroupIntroduction, userId);
                }
                if (_createIMGroupResult) {
                    // System.out.println("create im group ok 2");
                    _groupids.add(_lawyerGroupid);
                    memberIds.add(_lawyerGroupid);
                }

                //添加律师协作团队成员
                List<ProjectMember> _members = _stage.getMembers();
                insertProjectMember(_projectid, _stageid, _lawyerGroupid, _members, userId);

                //添加成员到im group
                List<Integer> _lawyerGroupMember = _members.stream().map(x -> x.getUserid()).distinct().collect(Collectors.toList());
                _imService.addIMGroupMember(_lawyerGroupid, _lawyerGroupMember, userId);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        map.put("client", clientIds);
        map.put("member", memberIds);

        map1.put("result", result);
        return map1;
    }

    //更新
    @Transactional
    public Map<String, Object> updateProject(ProjectSaveRequest _request, int userId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        int result = 0;

        //群组加颜色标记
        String color= RandomColorGenerator.getRandomRGB16();

        String _projectid = _request.getProjectid();
        int _projectType = _request.getProjecttype();

        List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);

        //if project name change
        List<String> _messageContent = new ArrayList<>();
        List<Map<String, String>> contentList = new ArrayList<>();
        List<CrmProjectMain> _theMains = getProjectMain(_projectid);
        String _projectName = "";
        if (_theMains != null && _theMains.size() > 0) {
            _projectName = _theMains.get(0).getProjectname();
            if (!_projectName.equals(_request.getName())) {
                CrmUser _theUser = _commonRepository.getUserInfo(userId);
                String _contentMessage = String.format("%s编辑了项目名称", _theUser.getRealname());
                _messageContent.add(_contentMessage);
                Map<String, String> cMap = new HashMap<>();
                cMap.put("content", _contentMessage);
                cMap.put("pushType", "0");
                contentList.add(cMap);
            }
        }

        //更新项目主数据
        result = updateProjectMain(_projectid, _request.getName());

        List<CrmProjectClient> _oldProjectClient = getProjectClient(_projectid);

        //对方委托人
        List<CrmProjectClient> _allProjectClinet = _oldProjectClient.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.Client.getPersonType()).collect(Collectors.toList());

        //对方当事人
        List<CrmProjectClient> _allLitigantList = _oldProjectClient.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.litigant.getPersonType()).collect(Collectors.toList());

        //删除委托人
        //deleteProjectClient(session, _projectid, _allProjectClinet);

        //获取 stage relate
        List<CrmProjectStageRelate> _oldStageRelates = getProjectStageRelate(_projectid);

        //项目当前关联的阶段
        List<CrmProjectStage> _savedStages = getProjectStageList(_projectid);

        //删除old  stage relate
        deleteProjectStageRelate(_oldStageRelates);

        //项目基本数据
        List<CrmProjectInfo> _projectInfos = getProjectInfo(_projectid);


        //读取合议庭和数据源
        List<CrmProjectContact> _projectContactList = getProjectContact(_projectid, userId);

        //删除合议庭和数据源
        deleteProjectContact(_projectContactList);

        //获取备注
        List<CrmProjectRemark> _remarks = getProjectRemark(_projectid, userId);

        //获取可以看到备注的人
        List<CrmProjectInfoRemarkViewer> _viewers = getProjectRemarkViewer(_projectid, userId);

        //读取老文件
        List<CrmProjectFile> _projectFileList = getProjectFiles(_projectid, userId);

        //删除老文件
        deleteProjectFiles(_projectFileList, userId);

        //删除老的任务
        List<CrmProjectTask> _tasks = getProjectTask(_projectid);
        deleteProjectTasks(_tasks);

        //获取项目成员
        List<CrmProjectMember> _memberList = getProjectMember(_projectid, userId);

        //需要添加的基本文件夹
        List<CrmProjectBasicFolder> _basicFolder = getProjectBasicFolder(_projectType);
        int _commonStageFolderType = BaseEnum.ProjectFolderType.Common.getProjectFolderType();
        List<CrmProjectBasicFolder> _commonStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _commonStageFolderType).collect(Collectors.toList());

        // 委托人的基本文件夹
        int _stageFolderType = BaseEnum.ProjectFolderType.Stage.getProjectFolderType();
        int _clientStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
        int _litigantFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();
        int _userDefineFolderType = BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType();

        List<CrmProjectBasicFolder> _clientStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _clientStageFolderType).collect(Collectors.toList());
        List<CrmProjectBasicFolder> _litigantStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _litigantFolderType).collect(Collectors.toList());

        List<ProjectStage> _stages = _request.getStages();


        List<CrmChatGroupPart> _savedGroups = getProjectChatGroup(_projectid);


        //获取项目的文件夹
        List<CrmProjectFolder> _savedFolders = getProjectFolder(_projectid, userId);

        //项目文件加类型
        List<CrmProjectFolder> _serviceProjectFolders = _savedFolders.stream().filter(x -> x.getFoldertype() == _commonStageFolderType).collect(Collectors.toList());

        //某个阶段编辑时候，可以使用的文件夹
        List<ProjectFolderResponse> _newStageFolders = new ArrayList<>();


        //删除已经移除的阶段文件夹
        List<CrmProjectFolder> _savedStageFolders = _savedFolders.stream().filter(x -> x.getFoldertype() == _stageFolderType).collect(Collectors.toList());
        for (CrmProjectFolder _f : _savedStageFolders) {
            if (_stages != null && _stages.size() > 0) {
                long _theStageCount = _stages.stream().filter(x -> x.getStageid() == _f.getStageid()).count();
                if (_theStageCount == 0) {
                    deleteProjectFolder(_f.getRecid(), userId);
                }
            } else {
                deleteProjectFolder(_f.getRecid(), userId);
            }
        }

        //获取项目的聊天分组
        //List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
        List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);

        // int _stageid = 0;
        for (ProjectStage _stage : _stages) {

            _newStageFolders.clear();

            int _stageid = _stage.getStageid();
            List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            String _stageName = _currentSageNameList.get(0).getStagename();

            //服务端阶段文件夹
            List<CrmProjectFolder> _serviceStageFolders = _savedFolders.stream().filter(x -> x.getFoldertype() == _stageFolderType).collect(Collectors.toList());

            //当前阶段的成员
            List<CrmProjectMember> _stageMembers = _memberList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());

            //循环之外已经删除了old stage relate s数据，这里只需要新增
            insertProjectStageRelate(_projectid, _stageid, _stage.getStageorder(), userId);

            //当前阶段的默认文件夹
            List<CrmProjectBasicFolder> _baseStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _stageFolderType).collect(Collectors.toList());

            //文件夹
            //如果新加了阶段，就新增文件夹，
            List<ProjectFolderResponse> _tmpStageFolders = _stage.getFolders();

            //新增阶段文件夹
            boolean _isStageFolderExist = true;
            if (_savedStages != null && _savedStages.size() > 0) {
                long _theStageCount = _savedStages.stream().filter(x -> x.getStageid() == _stageid).count();
                if (_theStageCount == 0) {
                    _isStageFolderExist = false;
                }
            } else {
                _isStageFolderExist = false;
            }

            //如果是新增的阶段，添加阶段文件夹
            if (!_isStageFolderExist) {
                for (CrmProjectBasicFolder _folder : _baseStageFolders) {
                    String _folderId = UUID.randomUUID().toString();
                    String _stageFolderName = "(" + _stageName + ")" + _folder.getRecname();
                    int _folderType = _folder.getRectype();
                    int _innerFolderType = _folder.getInnerfoldertype();
                    boolean _isLawyerFolder = false;
                    String _prefixName = "";
                    if (_folder.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolder.getDefaultFolderType()) {
                        _isLawyerFolder = true;
                        _prefixName = "律师协作团队";
                    }
                    insertProjectFolderBasic(_projectid, _stageid, _folderId, _stageFolderName, _stageFolderType, "", _prefixName, _innerFolderType, _isLawyerFolder, userId);

                    //把新增的文件夹放到文件夹池
                    ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                    _theServiceFolder.setClientid("");
                    _theServiceFolder.setFolderid(_folderId);
                    _theServiceFolder.setFoldername(_stageFolderName);
                    _theServiceFolder.setPartanme(_stageFolderName);
                    _theServiceFolder.setFoldertype(_folder.getRectype());
                    _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                    _theServiceFolder.setLawyerfolder(false);
                    _newStageFolders.add(_theServiceFolder);
                }
            }


            //委托人的更新,删除,新增操作
            List<ProjectClientGroup> _clientGroups = new ArrayList<>();
            int _personType = BaseEnum.PersonType.Client.getPersonType();
            List<ProjectClient> _clients = _stage.getInfo().getClient();
            List<CrmProjectClient> _savedClients = _allProjectClinet.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            if (_clients == null || _clients.size() == 0) {
                //删除委托人
                deleteProjectClientBatch(_savedClients);
                //删除委托人的聊天组
                for (CrmProjectClient _c : _savedClients) {
                    List<CrmChatGroupPart> _tmpChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == _stageid
                            && x.getRelatedid() != null
                            && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                    if (_tmpChatGroups != null && _tmpChatGroups.size() > 0) {
                        deleteProjectChatGroupBatch(_tmpChatGroups, userId);
                    }
                }

                //删除委托人的文件夹
                List<CrmProjectFolder> _tmpClientFolders = _savedFolders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _clientStageFolderType).collect(Collectors.toList());
                deleteProjectFolderBatch(_tmpClientFolders, userId);

                //删除委托人对应的成员
                List<CrmProjectMember> _oldStageMembers = _stageMembers.stream().filter(x -> x.getRelatedid() != null
                        && x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).collect(Collectors.toList());
                deleteProjectMember(_oldStageMembers, userId);

            } else {
                //如果没有老数据，就直接新增
                if (_savedClients == null || _savedClients.size() == 0) {
                    for (ProjectClient _c : _clients) {

                        //新增委托人
                        String _clinetRecid = UUID.randomUUID().toString();
                        insertProjectClientSingle(_projectid, _stageid, _personType, _clinetRecid, _c);

                        //新增文件夹
                        String _theStageFolderName = "(" + _stageName + ")";
                        boolean _isLawyerFolder = false;
                        if (_clientStageFolders != null && _clientStageFolders.size() > 0) {
                            for (CrmProjectBasicFolder _f : _clientStageFolders) {
                                int _innerFolderType = _f.getInnerfoldertype();
                                String _realFolderName = _theStageFolderName + _f.getRecname();
                                String _folderId = UUID.randomUUID().toString();
                                String _prefixName = _c.getName();
                                insertProjectFolderBasic(_projectid, _stageid, _folderId, _realFolderName, _clientStageFolderType, _clinetRecid, _prefixName, _innerFolderType, _isLawyerFolder, userId);

                                //把新增的文件夹放到文件夹池
                                ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                                _theServiceFolder.setClientid(_c.getClientid());
                                _theServiceFolder.setFolderid(_folderId);
                                _theServiceFolder.setFoldername(_realFolderName);
                                _theServiceFolder.setPartanme(_realFolderName);
                                _theServiceFolder.setFoldertype(_f.getRectype());
                                _theServiceFolder.setInnerfoldertype(_f.getInnerfoldertype());
                                _theServiceFolder.setLawyerfolder(false);
                                _newStageFolders.add(_theServiceFolder);
                            }
                        }


                        //新增聊天分组
                        int _chatType = BaseEnum.ChatType.Project.getChatType();
                        int _addGroupResult = 0;
                        String _clientGroupid = UUID.randomUUID().toString();
                        //im group name 最长30字节
                        String _groupName = "委托人协作团队";
                        String _imGroupName = "委托人协作团队";
                        String _groupIntroduction = "[" + _stageName + "]" + _projectName + "_委托人协作团队";


                        int _clientGroupType = BaseEnum.ChatGroupType.Client.getChatGroupType();
                        _addGroupResult = insertChatGroup(_clientGroupid, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _clinetRecid, _c.getName(), userId,color);
                        if (_addGroupResult > 0) {
                            _imService.createIMGroup(_clientGroupid, _imGroupName, _groupIntroduction, userId);
                        }

                        //添加委托人对应的成员
                        insertProjectMemberBatch(_projectid, _stageid, _clientGroupid, _c.getMembers(), _clinetRecid, userId);

                        //添加成员的到IM group
                        List<Integer> _theMemberIds = _c.getMembers().stream().map(ProjectMember::getUserid).collect(Collectors.toList());
                        if (_theMemberIds != null && _theMemberIds.size() > 0) {
                            _imService.addIMGroupMember(_clientGroupid, _theMemberIds, userId);
                        }

                        ProjectClientGroup _tmpClientGroup = new ProjectClientGroup();
                        _tmpClientGroup.setClientid(_c.getClientid());
                        _tmpClientGroup.setGroupid(_clientGroupid);
                        //_tmpClientGroup.setRecid();
                        _clientGroups.add(_tmpClientGroup);
                    }
                } else {

                    //更新
                    List<ProjectClient> _oldClients = _clients.stream().filter(x -> x.getRecid() != null
                            && !x.getRecid().isEmpty()).collect(Collectors.toList());
                    updateProjectClient(_oldClients);
                    for (ProjectClient _c : _oldClients) {

                        //更新聊天组名称
                        List<CrmChatGroupPart> _tmpGroups = _chatGroups.stream().filter(x -> x.getRelatedid() != null
                                && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());
                        updateProjectChatGroupNameBatch(_tmpGroups, _c.getName(), userId);

                        //更新文件夹名称
                        List<CrmProjectFolder> _tmpFolders = _savedFolders.stream().filter(x -> x.getStageid() == _stageid
                                && x.getRelatedid() != null
                                && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());
                        updateProjectFolderNameBatch(_tmpFolders, _c.getName(), userId);

                        //新增，更新，删除 委托人对应的成员
                        List<ProjectMember> _oldMembers = _c.getMembers().stream().filter(x -> x.getRecid() != null
                                && !x.getRecid().isEmpty()).collect(Collectors.toList());
                        List<ProjectMember> _newMembers = _c.getMembers().stream().filter(x -> x.getRecid() == null ||
                                x.getRecid().isEmpty()).collect(Collectors.toList());
                        List<CrmProjectMember> _savedMembers = _stageMembers.stream().filter(x -> x.getRelatedid() != null
                                && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                        //新增
                        String _memberGroupId = "";
                        if (_savedMembers != null && _savedMembers.size() > 0) {
                            _memberGroupId = _savedMembers.get(0).getGroupid();
                        } else {

                            //新增聊天分组
                            int _chatType = BaseEnum.ChatType.Project.getChatType();
                            int _addGroupResult = 0;
                            _memberGroupId = UUID.randomUUID().toString();
                            //im group name 最长30字节
                            String _groupName = "委托人协作团队";
                            String _imGroupName = "委托人协作团队";
                            String _groupIntroduction = "[" + _stageName + "]" + _projectName + "_委托人协作团队";
                            int _clientGroupType = BaseEnum.ChatGroupType.Client.getChatGroupType();
                            _addGroupResult = insertChatGroup(_memberGroupId, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _c.getRecid(), _c.getName(), userId,color);
                            if (_addGroupResult > 0) {
                                _imService.createIMGroup(_memberGroupId, _imGroupName, _groupIntroduction, userId);
                            }
                        }
                        //insertProjectMemberBatch(_projectid, _stageid, _memberGroupId, _newMembers, _c.getRecid(), userId);
                        for (ProjectMember _member : _newMembers) {
                            long _theMemberCount = _savedMembers.stream().filter(x -> x.getGrouptype() == _member.getGrouptype()
                                    && x.getInnergrouptype() == _member.getInnergrouptype() && x.getUserid() == _member.getUserid()).count();
                            if (_theMemberCount == 0) {
                                insertProjectMemberSingle(_projectid, _stageid, _memberGroupId, _member, _c.getRecid(), userId);
                            }
                        }

                        //添加member to im group
                        List<Integer> _theNewMemberIds = _newMembers.stream().map(ProjectMember::getUserid).collect(Collectors.toList());
                        if (_theNewMemberIds != null && _theNewMemberIds.size() > 0) {
                            _imService.addIMGroupMember(_memberGroupId, _theNewMemberIds, userId);
                        }

                        //更新和委托人关联的members
                        if (_oldMembers != null && _oldMembers.size() > 0) {
                            updateProjectMemberBatch(_oldMembers, userId);
                        }

                        //删除去掉了的成员
                        List<Integer> _theDeleteMembgerIds = new ArrayList<>();
                        for (CrmProjectMember _m : _savedMembers) {
                            if (_c.getMembers() != null) {
                                long _theMemberCount = _c.getMembers().stream().filter(x -> x.getGrouptype() == _m.getGrouptype()
                                        && x.getInnergrouptype() == _m.getInnergrouptype()
                                        && x.getUserid() == _m.getUserid()).count();
                                if (_theMemberCount == 0) {
                                    _theDeleteMembgerIds.add(_m.getUserid());
                                    deleteProjectMemberSingle(_m, userId);
                                }
                            }
                        }
                        //remove member from im group
                        if (_theDeleteMembgerIds.size() > 0) {
                            Optional<CrmChatGroupPart> _theClientChatGroup = _savedGroups.stream().filter(x -> x.getStageid() == _stageid
                                    && x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()
                                    && x.getRelatedid() != null && x.getRelatedid().equals(_c.getClientid())).findFirst();

                            String _theClientChatGroupId = "";
                            if (_theClientChatGroup.isPresent()) {
                                _theClientChatGroupId = _theClientChatGroup.get().getGroupid();
                            }
                            _imService.removeIMGroupMember(_theClientChatGroupId, _theDeleteMembgerIds, userId);
                        }
                    }

                    //删除
                    for (CrmProjectClient _c : _savedClients) {
                        List<ProjectClient> _tmp = _oldClients.stream().filter(x -> x.getRecid().equals(_c.getRecid())).collect(Collectors.toList());
                        if (_tmp == null || _tmp.size() == 0) {
                            deleteProjectClient(_c.getRecid());

                            //删除文件夹
                            int _clientFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
                            List<CrmProjectFolder> _tmpFolders = _savedFolders.stream()
                                    .filter(x -> x.getStageid() == _stageid
                                            && x.getFoldertype() == _clientFolderType
                                            && x.getRelatedid() != null
                                            && x.getRelatedid().equals(_c.getRecid()))
                                    .collect(Collectors.toList());

                            deleteProjectFolderBatch(_tmpFolders, userId);

                            //删除聊天分组
                            List<CrmChatGroupPart> _tmpChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == _stageid
                                    && x.getRelatedid() != null
                                    && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                            deleteProjectChatGroupBatch(_tmpChatGroups, userId);


                            //删除委托人对应的成员
                            List<CrmProjectMember> _tmpClientMembers = _stageMembers.stream().filter(x -> x.getRelatedid() != null
                                    && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                            // deleteProjectMember(session, _tmpClientMembers, userId);

                        }
                    }

                    //新增
                    List<ProjectClient> _newClients = _clients.stream().filter(x -> x.getRecid() == null || x.getRecid().equals("")).collect(Collectors.toList());
                    for (ProjectClient _c : _newClients) {

                        //新增委托人
                        String _clinetRecid = UUID.randomUUID().toString();
                        insertProjectClientSingle(_projectid, _stageid, _personType, _clinetRecid, _c);

                        //新增文件夹
                        String _theStageFolderName = "(" + _stageName + ")";
                        boolean _isLawyerFolder = false;
                        if (_clientStageFolders != null && _clientStageFolders.size() > 0) {
                            for (CrmProjectBasicFolder _f : _clientStageFolders) {
                                int _innerFolderType = _f.getInnerfoldertype();
                                String _realFolderName = _theStageFolderName + _f.getRecname();
                                String _folderId = UUID.randomUUID().toString();
                                String _prefixName = _c.getName();
                                insertProjectFolderBasic(_projectid, _stageid, _folderId, _realFolderName, _clientStageFolderType, _clinetRecid, _prefixName, _innerFolderType, _isLawyerFolder, userId);

                                //把新增的文件夹放到文件夹池
                                ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                                _theServiceFolder.setClientid(_c.getClientid());
                                _theServiceFolder.setFolderid(_folderId);
                                _theServiceFolder.setFoldername(_realFolderName);
                                _theServiceFolder.setPartanme(_realFolderName);
                                _theServiceFolder.setFoldertype(_f.getRectype());
                                _theServiceFolder.setInnerfoldertype(_f.getInnerfoldertype());
                                _theServiceFolder.setLawyerfolder(false);
                                _newStageFolders.add(_theServiceFolder);
                            }
                        }


                        //新增聊天分组
                        int _chatType = BaseEnum.ChatType.Project.getChatType();
                        int _addGroupResult = 0;
                        String _clientGroupid = UUID.randomUUID().toString();
                        //im group name 最长30字节
                        String _groupName = "委托人协作团队";
                        String _imGroupName = "委托人协作团队";
                        String _groupIntroduction = "[" + _stageName + "]" + _projectName + "_委托人协作团队";
                        int _clientGroupType = BaseEnum.ChatGroupType.Client.getChatGroupType();
                        _addGroupResult = insertChatGroup(_clientGroupid, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _clinetRecid, _c.getName(), userId,color);
                        if (_addGroupResult > 0) {
                            _imService.createIMGroup(_clientGroupid, _imGroupName, _groupIntroduction, userId);
                        }

                        //添加委托人对应的成员
                        insertProjectMemberBatch(_projectid, _stageid, _clientGroupid, _c.getMembers(), _clinetRecid, userId);

                        //添加member to im group
                        List<ProjectMember> _theClientMembers = _c.getMembers();
                        if (_theClientMembers != null && _theClientMembers.size() > 0) {
                            List<Integer> _theNewMemberIds = _theClientMembers.stream().map(ProjectMember::getUserid).collect(Collectors.toList());
                            if (_theNewMemberIds != null && _theNewMemberIds.size() > 0) {
                                _imService.addIMGroupMember(_clientGroupid, _theNewMemberIds, userId);
                            }
                        }

                        ProjectClientGroup _tmpClientGroup = new ProjectClientGroup();
                        _tmpClientGroup.setClientid(_c.getClientid());
                        _tmpClientGroup.setGroupid(_clientGroupid);
                        _clientGroups.add(_tmpClientGroup);
                    }
                }
            }

            //添加 对方当事人
            List<ProjectClient> _litigants = _stage.getInfo().getLitigant();
            _personType = BaseEnum.PersonType.litigant.getPersonType();
            List<CrmProjectClient> _savedLitigants = _allLitigantList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            if (_litigants == null || _litigants.size() == 0) {

                //删除委托人
                deleteProjectClientBatch(_savedLitigants);

                //删除委托人的文件夹
                List<CrmProjectFolder> _tmpLitigantFolders = _savedFolders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _litigantFolderType).collect(Collectors.toList());
                deleteProjectFolderBatch(_tmpLitigantFolders, userId);

            } else {
                if (_savedLitigants == null || _savedLitigants.size() == 0) {
                    for (ProjectClient _c : _litigants) {
                        //新增对方当事人
                        String _litigantRecid = UUID.randomUUID().toString();
                        insertProjectClientSingle(_projectid, _stageid, _personType, _litigantRecid, _c);

                        //新增对方当事人文件夹
                        String _theStageFolderName = "(" + _stageName + ")";

                        boolean _isLawyerFolder = false;
                        if (_litigantStageFolders != null && _litigantStageFolders.size() > 0) {
                            for (CrmProjectBasicFolder _f : _litigantStageFolders) {
                                int _innerFolderType = _f.getInnerfoldertype();
                                String _realFolderName = _theStageFolderName + _f.getRecname();
                                String _folderId = UUID.randomUUID().toString();
                                String _prefixName = _c.getName();
                                insertProjectFolderBasic(_projectid, _stageid, _folderId, _realFolderName, _litigantFolderType, _litigantRecid, _prefixName, _innerFolderType, _isLawyerFolder, userId);

                                //把新增的文件夹放到文件夹池
                                ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                                _theServiceFolder.setClientid(_c.getClientid());
                                _theServiceFolder.setFolderid(_folderId);
                                _theServiceFolder.setFoldername(_realFolderName);
                                _theServiceFolder.setPartanme(_realFolderName);
                                _theServiceFolder.setFoldertype(_f.getRectype());
                                _theServiceFolder.setInnerfoldertype(_f.getInnerfoldertype());
                                _theServiceFolder.setLawyerfolder(false);
                                _newStageFolders.add(_theServiceFolder);
                            }
                        }
                    }
                } else {
                    //删除去掉的
                    List<ProjectClient> _oldLitigantList = _litigants.stream().filter(x -> x.getRecid() != null && !x.getRecid().isEmpty()).collect(Collectors.toList());
                    for (CrmProjectClient _c : _savedLitigants) {
                        List<ProjectClient> _tmp = _oldLitigantList.stream().filter(x -> x.getRecid().equals(_c.getRecid())).collect(Collectors.toList());
                        if (_tmp == null || _tmp.size() == 0) {
                            //删除对方当事人
                            deleteProjectClient(_c.getRecid());
                            //删除文件夹
                            List<CrmProjectFolder> _tmpfolders = _savedFolders
                                    .stream()
                                    .filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _litigantFolderType
                                            && x.getRelatedid() != null
                                            && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                            if (_tmpfolders != null && _tmpfolders.size() > 0) {
                                deleteProjectFolderBatch(_tmpfolders, userId);
                            }
                        }
                    }

                    //更新老的对方当事人
                    updateProjectClient(_oldLitigantList);

                    //更新文件夹名称
                    for (ProjectClient _c : _oldLitigantList) {
                        List<CrmProjectFolder> _tmpFolders = _savedFolders.stream().filter(x -> x.getStageid() == _stageid
                                && x.getRelatedid() != null
                                && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());

                        updateProjectFolderNameBatch(_tmpFolders, _c.getName(), userId);
                    }

                    //添加新的
                    List<ProjectClient> _newLitigantList = _litigants.stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).collect(Collectors.toList());
                    if (_newLitigantList != null && _newLitigantList.size() > 0) {
                        for (ProjectClient _c : _newLitigantList) {
                            //新增对方当事人
                            String _litigantRecid = UUID.randomUUID().toString();
                            insertProjectClientSingle(_projectid, _stageid, _personType, _litigantRecid, _c);

                            //新增对方当事人文件夹
                            //新增文件夹
                            String _theStageFolderName = "(" + _stageName + ")";
                            boolean _isLawyerFolder = false;
                            if (_litigantStageFolders != null && _litigantStageFolders.size() > 0) {
                                for (CrmProjectBasicFolder _f : _litigantStageFolders) {
                                    int _innerFolderType = _f.getInnerfoldertype();
                                    String _realFolderName = _theStageFolderName + _f.getRecname();
                                    String _folderId = UUID.randomUUID().toString();
                                    String _prefixName = _c.getName();
                                    insertProjectFolderBasic(_projectid, _stageid, _folderId, _realFolderName, _litigantFolderType, _litigantRecid, _prefixName, _innerFolderType, _isLawyerFolder, userId);

                                    //把新增的文件夹放到文件夹池
                                    ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                                    _theServiceFolder.setClientid(_c.getClientid());
                                    _theServiceFolder.setFolderid(_folderId);
                                    _theServiceFolder.setFoldername(_realFolderName);
                                    _theServiceFolder.setPartanme(_realFolderName);
                                    _theServiceFolder.setFoldertype(_f.getRectype());
                                    _theServiceFolder.setInnerfoldertype(_f.getInnerfoldertype());
                                    _theServiceFolder.setLawyerfolder(false);
                                    _newStageFolders.add(_theServiceFolder);
                                }
                            }
                        }
                    }
                }
            }

            //获取项目基本信息
            boolean _hasInfo = false;
            CrmProjectInfo _currentInfo = new CrmProjectInfo();
            for (CrmProjectInfo _info : _projectInfos) {
                if (_info.getStageid() == _stageid) {
                    _currentInfo = _info;
                    _hasInfo = true;
                    break;
                }
            }

            if (_hasInfo) {
                //更新基本信息
                updateProjectInfo(_stage, _currentInfo.getRecid());
            } else {
                insertProjectInfo(_projectid, _stage, userId);
            }

            //新增合议庭和数据源
            //新增合议庭
            int _contactType = BaseEnum.ContactType.FullCount.getContactType();
            List<ProjectContact> _fullCount = _stage.getInfo().getFullcourt();
            insertProjectContact(_projectid, _stageid, _contactType, _fullCount, userId);

            //新增书记员
            _contactType = BaseEnum.ContactType.Clerk.getContactType();
            List<ProjectContact> _clerks = _stage.getInfo().getClerk();
            insertProjectContact(_projectid, _stageid, _contactType, _clerks, userId);

            //编辑备注和可以看到备注的人
            List<ProjectRemark> _newRemarks = _stage.getInfo().getRemarks();
            List<ProjectRemark> _myNewRemarks = new ArrayList<>();
            if (_newRemarks != null && _newRemarks.size() > 0) {
                _myNewRemarks = _newRemarks.stream().filter(x -> x.getCreatorid() == userId).collect(Collectors.toList());
            }

            List<CrmProjectInfoRemarkViewer> _currentOldViewer = new ArrayList<>();
            if (_viewers != null && _viewers.size() > 0) {
                _currentOldViewer = _viewers.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            }

            //更新或者新增，自己的备注
            if (_myNewRemarks != null && _myNewRemarks.size() > 0) {

                for (ProjectRemark _remark : _myNewRemarks) {
                    String _tempRemarkid = _remark.getRecid();
                    String _remarkid = UUID.randomUUID().toString();
                    if (_tempRemarkid == null || _tempRemarkid.equals("")) {
                        //insert
                        insertProjectRemark(_projectid, _stageid, _remarkid, _remark.getContent(), userId);
                        List<ProjectInfoRemarkViewer> _viewList = _remark.getViewer();
                        if (_viewList != null && _viewList.size() > 0) {
                            insertProjectRemarkViewers(_projectid, _stageid, _remarkid, _viewList, userId);
                        }
                    } else {

                        //update
                        updateProjectRemark(_remark.getRecid(), _remark.getContent(), userId);

                        List<ProjectInfoRemarkViewer> _viewList = _remark.getViewer();
                        //old data
                        List<CrmProjectInfoRemarkViewer> _currentOldRemarkViewer = new ArrayList<>();
                        if (_currentOldViewer != null && _currentOldViewer.size() > 0) {
                            _currentOldRemarkViewer = _currentOldViewer.stream().filter(x -> x.getRemarkid().equals(_remark.getRecid())).collect(Collectors.toList());
                        }


                        if (_viewList != null && _viewList.size() > 0) {
                            for (ProjectInfoRemarkViewer _v : _viewList) {
                                if (_v.getRecid() == null || _v.getRecid().equals("")) {
                                    insertProjectRemarkViewer(_projectid, _stageid, _remark.getRecid(), _v.getUserid(), userId);
                                }
                            }
                            for (CrmProjectInfoRemarkViewer _v2 : _currentOldRemarkViewer) {
                                List<ProjectInfoRemarkViewer> _tmp2 = _viewList.stream().filter(x -> x.getRecid() != null && x.getRecid().equals(_v2.getRecid())).collect(Collectors.toList());
                                if (_tmp2 == null || _tmp2.size() == 0) {
                                    deleteProjectRemarkViewer(_v2.getRecid());
                                }
                            }
                        } else {
                            if (_currentOldRemarkViewer != null && _currentOldRemarkViewer.size() > 0) {
                                deleteProjectRemarkViewers(_currentOldRemarkViewer);
                            }
                        }
                    }
                }

                //delete old remark
                if (_remarks != null && _remarks.size() > 0) {
                    List<CrmProjectRemark> _tmpRemarks = _remarks.stream().filter(x -> x.getStageid() == _stageid && x.getReccreator() == userId).collect(Collectors.toList());
                    if (_tmpRemarks != null && _tmpRemarks.size() > 0) {

                        for (CrmProjectRemark _r : _tmpRemarks) {
                            List<ProjectRemark> _tmpRemark = _myNewRemarks.stream().filter(x -> x.getRecid() != null && x.getRecid().equals(_r.getRecid())).collect(Collectors.toList());
                            if (_tmpRemark == null || _tmpRemark.size() == 0) {
                                deleteProjectRemark(_r.getRecid(), userId);
                            }
                        }
                    }
                }

            } else {
                if (_remarks != null && _remarks.size() > 0) {
                    List<CrmProjectRemark> _tmpRemarks = _remarks.stream().filter(x -> x.getStageid() == _stageid && x.getReccreator() == userId).collect(Collectors.toList());
                    if (_tmpRemarks != null && _tmpRemarks.size() > 0) {
                        deleteProjectRemarks(_tmpRemarks, userId);
                    }
                }
            }


            //新增文件
            List<ProjectFileFolder> _fileFolders = _stage.getFiles();
            if (_fileFolders != null && _fileFolders.size() > 0) {
                for (ProjectFileFolder _folder : _fileFolders) {
                    int _theFolderType = _folder.getFoldertype();
                    List<ProjectFile> _theFiles = _folder.getItems();
                    if (_theFolderType == _commonStageFolderType) {

                        //从服务端文件夹中找到对应的文件夹
                        String _theFolerid = "";
                        Optional<CrmProjectFolder> _theServiceFolder = _serviceProjectFolders.stream().filter(x -> x.getFoldertype() == _folder.getFoldertype()
                                && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();

                        if (_theServiceFolder.isPresent()) {
                            CrmProjectFolder _serviceFolder = _theServiceFolder.get();
                            _theFolerid = _serviceFolder.getRecid();
                        }

                        //添加文件
                        if (_theFiles != null && _theFiles.size() > 0) {
                            for (ProjectFile _f : _theFiles) {
                                String _fileRecid = UUID.randomUUID().toString();
                                _f.setFolderid(_theFolerid);
                                //把文件写入数据库
                                insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                            }
                        }
                    } else if (_theFolderType == _stageFolderType) {

                        //从服务端文件夹中找到对应的文件夹
                        String _theFolerid = "";
                        Optional<CrmProjectFolder> _theServiceFolder = _savedStageFolders.stream().filter(x -> x.getFoldertype() == _folder.getFoldertype()
                                && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                        if (_theServiceFolder.isPresent()) {
                            CrmProjectFolder _serviceFolder = _theServiceFolder.get();
                            _theFolerid = _serviceFolder.getRecid();
                        }

                        if (_theFolerid.isEmpty()) {
                            Optional<ProjectFolderResponse> _theNewStageFolder = _newStageFolders.stream().filter(x -> x.getFoldertype() == _folder.getFoldertype()
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                            if (_theNewStageFolder.isPresent()) {
                                _theFolerid = _theNewStageFolder.get().getFolderid();
                            }
                        }

                        if (_theFiles != null && _theFiles.size() > 0) {
                            for (ProjectFile _f : _theFiles) {
                                String _fileRecid = UUID.randomUUID().toString();
                                _f.setFolderid(_theFolerid);
                                //把文件写入数据库
                                insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                            }
                        }
                    } else if (_theFolderType == _userDefineFolderType) {

                        //把文件写入数据库
                        //不安全呀
                        String _theFolderId = "";
                        Optional<CrmProjectFolder> _theUserDefineFolder = _savedFolders.stream().filter(x -> x.getFoldertype() == _userDefineFolderType
                                && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                        if (_theUserDefineFolder.isPresent()) {
                            _theFolderId = _theUserDefineFolder.get().getRecid();
                        }

                        if (_theFolderId.isEmpty()) {
                            Optional<ProjectFolderResponse> _theNewStageFolder = _newStageFolders.stream().filter(x -> x.getFoldertype() == _userDefineFolderType
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                            if (_theNewStageFolder.isPresent()) {
                                _theFolderId = _theNewStageFolder.get().getFolderid();
                            }
                        }

                        if (_theFiles != null && _theFiles.size() > 0) {
                            for (ProjectFile _f : _theFiles) {
                                String _fileRecid = UUID.randomUUID().toString();
                                _f.setFolderid(_theFolderId);
                                insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                            }
                        }
                    } else {

                        //找到服务端对应的文件夹
                        String _theFolerid = "";
                        String _theClientId = _folder.getClientid();
                        Optional<CrmProjectFolder> _theServiceFolder = _savedFolders.stream().filter(x -> x.getRelatedid() != null && x.getRelatedid().equals(_theClientId)
                                && x.getFoldertype() == _folder.getFoldertype()
                                && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();

                        if (_theServiceFolder.isPresent()) {
                            CrmProjectFolder _serviceFolder = _theServiceFolder.get();
                            _theFolerid = _serviceFolder.getRecid();
                        }
                        if (_theFolerid.isEmpty()) {
                            Optional<ProjectFolderResponse> _theNewClientFolder = _newStageFolders.stream().filter(x -> x.getClientid().equals(_theClientId)
                                    && x.getFoldertype() == _folder.getFoldertype()
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();

                            if (_theNewClientFolder.isPresent()) {
                                _theFolerid = _theNewClientFolder.get().getFolderid();
                            }
                        }
                        //把文件写入数据库
                        if (_theFiles != null && _theFiles.size() > 0) {
                            for (ProjectFile _f : _theFiles) {
                                String _fileRecid = UUID.randomUUID().toString();
                                _f.setFolderid(_theFolerid);
                                insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                            }
                        }
                    }
                    //end of folder type
                }
            }


            //新增项目任务
            List<ProjectTask> _taskList = _stage.getTasks();
            insertProjectTasks(_projectid, _stageid, _taskList, userId);

            //更新项目成员的管理员，主办人身份
            List<ProjectMember> _membersRequest = _stage.getMembers();
            List<ProjectMember> _savedMembers = _membersRequest.stream().filter(x -> x.getRecid() != null && !x.getRecid().isEmpty()).collect(Collectors.toList());
            if (_savedMembers != null && _savedMembers.size() > 0) {
                updateProjectMemberBatch(_savedMembers, userId);
            }

            //更新律师协作团队成员
            int _lawyerGroupType = BaseEnum.GroupType.Lawyer.getGroupType();
            //已经保存的律师协作团队成员
            List<CrmProjectMember> _savedStageLaywerMembers = _memberList.stream().filter(x -> x.getStageid() == _stageid && x.getGrouptype() == _lawyerGroupType).collect(Collectors.toList());

            //projectMemmberEdit(_projectid, _stageid, _membersRequest, _savedStageLaywerMembers, userId);

            //删除已经删除的老成员
            for (CrmProjectMember _m : _savedStageLaywerMembers) {
                if (_membersRequest != null) {
                    long _theCount = _membersRequest.stream().filter(x -> x.getUserid() == _m.getUserid()).count();
                    if (_theCount == 0) {
                        //delete the meber
                        deleteProjectMemberSingle(_m, userId);
                        //todo:delete the member from im group
                    }
                }
            }

            //插入新成员
            String _groupid = "";
            Optional<CrmChatGroupPart> _theChatGroup = _savedGroups.stream().filter(x -> x.getStageid() == _stageid
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();
            if (_theChatGroup.isPresent()) {
                _groupid = _theChatGroup.get().getGroupid();
            }
            if (_membersRequest != null && _membersRequest.size() > 0) {
                List<ProjectMember> _newMembers = _membersRequest.stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).collect(Collectors.toList());
                if (_newMembers != null && _newMembers.size() > 0) {
                    for (ProjectMember _member : _newMembers) {
                        long _theLawyerMemberCount = _savedStageLaywerMembers.stream().filter(x -> x.getUserid() == _member.getUserid()).count();
                        if (_theLawyerMemberCount == 0) {
                            //添加团队成员
                            // insertProjectMember(_projectid, _stageid, _groupid, _newMembers, userId);
                            insertProjectMemberSingle(_projectid, _stageid, _groupid, _member, "", userId);
                            //todo:把新成员添加到im group
                        }
                    }
                }
            }

            //把发送数据变更消息放在最后，防止异常发生
            try {

                List<CrmProjectMember> _theLawyerMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == _lawyerGroupType).collect(Collectors.toList());

                List<CrmProjectMember> _theClientGroupMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()
                        && x.getInnergrouptype() == BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType()).collect(Collectors.toList());

                List<CrmProjectMember> _theLawyerAgentGroupMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()
                        && x.getInnergrouptype() == BaseEnum.InnerGroupType.LawyerGroup.getInnerGroupType()).collect(Collectors.toList());


                List<ProjectMember> _theRequestLawyerMembers = _membersRequest.stream().filter(x -> x.getGrouptype() == _lawyerGroupType).collect(Collectors.toList());

                List<ProjectMember> _theRequestClientGroupMembers = _membersRequest.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()
                        && x.getInnergrouptype() == BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType()).collect(Collectors.toList());

                List<ProjectMember> _theRequestLawyerAgentGroupMembers = _membersRequest.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()
                        && x.getInnergrouptype() == BaseEnum.InnerGroupType.LawyerGroup.getInnerGroupType()).collect(Collectors.toList());


                //判断成员是否发生了改变
                boolean _isMeberChanged = false;
                _isMeberChanged = _commonRepository.isRequestMemberExists(_theRequestLawyerMembers, _theLawyerMembers);
                if (!_isMeberChanged) {
                    _isMeberChanged = _commonRepository.isSavedMemberExists(_theLawyerMembers, _theRequestLawyerMembers);
                }
                if (!_isMeberChanged) {
                    _isMeberChanged = _commonRepository.isRequestMemberExists(_theRequestClientGroupMembers, _theClientGroupMembers);
                }
                if (!_isMeberChanged) {
                    _isMeberChanged = _commonRepository.isSavedMemberExists(_theClientGroupMembers, _theRequestClientGroupMembers);
                }
                if (!_isMeberChanged) {
                    _isMeberChanged = _commonRepository.isRequestMemberExists(_theRequestLawyerAgentGroupMembers, _theLawyerAgentGroupMembers);
                }
                if (!_isMeberChanged) {
                    _isMeberChanged = _commonRepository.isSavedMemberExists(_theLawyerAgentGroupMembers, _theRequestLawyerAgentGroupMembers);
                }

                //发送了成员变更群组消息
                if (_isMeberChanged) {
                    CrmUser _theUser = _commonRepository.getUserInfo(userId);
                    String _content = String.format("%s调整了成员", _theUser.getRealname());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }


                Optional<CrmProjectMember> __theLawyerMembersHost = _theLawyerMembers.stream().filter(x -> x.ishost()).findFirst();
                Optional<CrmProjectMember> __theLawyerMembersManager = _theLawyerMembers.stream().filter(x -> x.getIsmanager()).findFirst();

                Optional<CrmProjectMember> _theClientGroupMembersHost = _theClientGroupMembers.stream().filter(x -> x.ishost()).findFirst();
                Optional<CrmProjectMember> _theClientGroupMembersManager = _theClientGroupMembers.stream().filter(x -> x.getIsmanager()).findFirst();

                Optional<CrmProjectMember> _theLawyerAgentGroupMembersHost = _theLawyerAgentGroupMembers.stream().filter(x -> x.ishost()).findFirst();
                Optional<CrmProjectMember> _theLawyerAgentGroupMembersManager = _theLawyerAgentGroupMembers.stream().filter(x -> x.getIsmanager()).findFirst();


                // the request data
                Optional<ProjectMember> _theRequestLawyerMembersHost = _theRequestLawyerMembers.stream().filter(x -> x.getIshost()).findFirst();
                Optional<ProjectMember> _theRequestLawyerMembersManager = _theRequestLawyerMembers.stream().filter(x -> x.getIsmanager()).findFirst();

                Optional<ProjectMember> _theRequestClientGroupMembersHost = _theRequestClientGroupMembers.stream().filter(x -> x.getIshost()).findFirst();
                Optional<ProjectMember> _theRequestClientGroupMembersManager = _theRequestClientGroupMembers.stream().filter(x -> x.getIsmanager()).findFirst();

                Optional<ProjectMember> _theRequestLawyerAgentGroupMembersHost = _theRequestLawyerAgentGroupMembers.stream().filter(x -> x.getIshost()).findFirst();
                Optional<ProjectMember> _theRequestLawyerAgentGroupMembersManger = _theRequestLawyerAgentGroupMembers.stream().filter(x -> x.getIsmanager()).findFirst();


                if (_theRequestLawyerMembersHost.get().getUserid() != __theLawyerMembersHost.get().getUserid()) {
                    CrmUser _theUser = _commonRepository.getUserInfo(_theRequestLawyerMembersHost.get().getUserid());
                    String _content = String.format("律师协作团队主办人变更为%s", _theUser.getRealname());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }
                if (_theRequestLawyerMembersManager.get().getUserid() != __theLawyerMembersManager.get().getUserid()) {

                    CrmUser _theUser = _commonRepository.getUserInfo(_theRequestLawyerMembersManager.get().getUserid());
                    String _content = String.format("律师协作团队管理员变更为%s", _theUser.getRealname());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                if (_theRequestClientGroupMembersHost.isPresent() && _theClientGroupMembersHost.isPresent()) {
                    if (_theRequestClientGroupMembersManager.get().getUserid() != _theClientGroupMembersManager.get().getUserid()) {
                        CrmUser _theUser = _commonRepository.getUserInfo(_theRequestClientGroupMembersManager.get().getUserid());
                        String _content = String.format("委托人组管理员变更为%s", _theUser.getRealname());
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }
                } else {

                    if (_theRequestClientGroupMembersHost.isPresent() && !_theClientGroupMembersHost.isPresent()) {
                        CrmUser _theUser = _commonRepository.getUserInfo(_theRequestClientGroupMembersManager.get().getUserid());
                        String _content = String.format("委托人组管理员变更为%s", _theUser.getRealname());
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }
                }


                if (_theRequestLawyerAgentGroupMembersHost.isPresent() && _theLawyerAgentGroupMembersHost.isPresent()) {
                    if (_theRequestLawyerAgentGroupMembersHost.get().getUserid() != _theLawyerAgentGroupMembersHost.get().getUserid()) {
                        CrmUser _theUser = _commonRepository.getUserInfo(_theRequestLawyerAgentGroupMembersHost.get().getUserid());
                        String _content = String.format("律师代理组主办人变更为%s", _theUser.getRealname());
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }
                } else {

                    if (_theRequestLawyerAgentGroupMembersHost.isPresent() && !_theLawyerAgentGroupMembersHost.isPresent()) {
                        CrmUser _theUser = _commonRepository.getUserInfo(_theRequestLawyerAgentGroupMembersHost.get().getUserid());
                        String _content = String.format("律师代理组主办人变更为%s", _theUser.getRealname());
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }
                }
                if (_theRequestLawyerAgentGroupMembersManger.isPresent() && _theLawyerAgentGroupMembersManager.isPresent()) {

                    if (_theRequestLawyerAgentGroupMembersManger.get().getUserid() != _theLawyerAgentGroupMembersManager.get().getUserid()) {

                        CrmUser _theUser = _commonRepository.getUserInfo(_theRequestLawyerAgentGroupMembersManger.get().getUserid());
                        String _content = String.format("律师代理组管理员变更为%s", _theUser.getRealname());
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);

                    }
                } else {
                    if (_theRequestLawyerAgentGroupMembersManger.isPresent() && !_theLawyerAgentGroupMembersManager.isPresent()) {

                        CrmUser _theUser = _commonRepository.getUserInfo(_theRequestLawyerAgentGroupMembersManger.get().getUserid());
                        String _content = String.format("律师代理组管理员变更为%s", _theUser.getRealname());
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }

                }


                //文件
                boolean _hasFileUpload = false;
                boolean _hasFileDelete = false;
                boolean _hasFileRename = false;


                List<CrmProjectFile> _theSavedStageFiles = _projectFileList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                for (ProjectFileFolder f : _fileFolders) {
                    List<CrmProjectFile> _filesOfFolder = _theSavedStageFiles.stream().filter(x -> x.getFolderid().equals(f.getFolderid())).collect(Collectors.toList());
                    if (_filesOfFolder.size() == 0) {
                        if (f.getItems() != null && f.getItems().size() > 0) {
                            _hasFileUpload = true;
                        }
                    } else {
                        if (f.getItems() != null && f.getItems().size() > 0) {
                            for (ProjectFile _f : f.getItems()) {
                                long _theNewFileCount = _filesOfFolder.stream().filter(x -> x.getUploadfileid().equals(_f.getUploadfileid())).count();
                                if (_theNewFileCount == 0) {
                                    _hasFileUpload = true;
                                }
                            }
                        }
                    }
                    for (CrmProjectFile _file : _filesOfFolder) {
                        if (f.getItems() != null && f.getItems().size() > 0) {
                            Optional<ProjectFile> _theFile = f.getItems().stream().filter(x -> checkNull(x.getUploadfileid()).equals(_file.getUploadfileid())).findFirst();
                            if (_theFile.isPresent()) {
                                if (!_theFile.get().getFilename().equals(_file.getFilename())) {
                                    _hasFileRename = true;
                                }
                            } else {
                                _hasFileDelete = true;
                            }
                        }
                    }
                }

                if (_theSavedStageFiles != null && _theSavedStageFiles.size() > 0) {
                    for (CrmProjectFile _file : _theSavedStageFiles) {
                        List<ProjectFileFolder> _theFileFolder = _fileFolders.stream().filter(x -> x.getFolderid().equals(_file.getFolderid())).collect(Collectors.toList());
                        if (_theFileFolder != null && _theFileFolder.size() > 0) {


                        } else {
                            _hasFileDelete = true;
                        }
                    }
                } else {

                    if (_fileFolders != null && _fileFolders.size() > 0) {
                        for (ProjectFileFolder ff : _fileFolders) {
                            if (ff.getItems() != null && ff.getItems().size() > 0) {
                                _hasFileUpload = true;
                                break;
                            }
                        }
                    }
                }

                String _userName = _commonRepository.getUserInfo(userId).getRealname();
                if (_hasFileUpload) {
                    String _content = String.format("%s上传了文件", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                if (_hasFileDelete) {
                    String _content = String.format("%s删除了文件", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                if (_hasFileRename) {
                    String _content = String.format("%s重命名了文件", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }


                //用户姓名编辑了字段名称
                boolean _isClientChanged = false;
                boolean _isLitigantChanged = false;

                //_savedClients
                if (_clients != null && _clients.size() > 0) {
                    if (_savedClients != null && _savedClients.size() > 0) {
                        for (ProjectClient c : _clients) {

                            long _theClientCount = _savedClients.stream().filter(x -> checkNull(x.getTitle()).equals(checkNull(c.getTitle()))
                                    && checkNull(x.getName()).equals(checkNull(c.getName()))
                                    && checkNull(x.getContact()).equals(checkNull(c.getContact()))
                                    && checkNull(x.getPhone()).equals(checkNull(c.getPhone())) && checkNull(x.getMail()).equals(checkNull(c.getMail()))).count();

                            if (_theClientCount == 0) {
                                _isClientChanged = true;
                            }
                        }
                    } else {
                        _isClientChanged = true;
                    }
                } else {
                    if (_savedClients != null && _savedClients.size() > 0) {
                        _isClientChanged = true;
                    }
                }

                if (_savedClients != null && _savedClients.size() > 0) {
                    if (_clients != null && _clients.size() > 0) {
                        for (CrmProjectClient c : _savedClients) {

                            long _theClientCount = _clients.stream().filter(x -> checkNull(x.getTitle()).equals(checkNull(c.getTitle()))
                                    && checkNull(x.getName()).equals(checkNull(c.getName()))
                                    && checkNull(x.getContact()).equals(checkNull(c.getContact()))
                                    && checkNull(x.getPhone()).equals(checkNull(c.getPhone())) && checkNull(x.getMail()).equals(checkNull(c.getMail()))).count();

                            if (_theClientCount == 0) {
                                _isClientChanged = true;
                            }
                        }
                    } else {
                        _isClientChanged = true;
                    }
                } else {
                    if (_clients != null && _clients.size() > 0) {
                        _isClientChanged = true;
                    }
                }

                //_litigants
                if (_litigants != null && _litigants.size() > 0) {
                    if (_savedLitigants != null && _savedLitigants.size() > 0) {
                        for (ProjectClient c : _litigants) {

                            long _theClientCount = _savedLitigants.stream().filter(x -> checkNull(x.getTitle()).equals(checkNull(c.getTitle()))
                                    && checkNull(x.getName()).equals(checkNull(c.getName()))
                                    && checkNull(x.getContact()).equals(checkNull(c.getContact()))
                                    && checkNull(x.getPhone()).equals(checkNull(c.getPhone())) && checkNull(x.getMail()).equals(checkNull(c.getMail()))).count();


                            if (_theClientCount == 0) {
                                _isLitigantChanged = true;
                            }
                        }
                    } else {
                        _isLitigantChanged = true;
                    }
                } else {
                    if (_savedLitigants != null && _savedLitigants.size() > 0) {
                        _isLitigantChanged = true;
                    }
                }

                if (_savedLitigants != null && _savedLitigants.size() > 0) {
                    if (_litigants != null && _litigants.size() > 0) {
                        for (CrmProjectClient c : _savedLitigants) {

                            long _theClientCount = _litigants.stream().filter(x -> checkNull(x.getTitle()).equals(checkNull(c.getTitle()))
                                    && checkNull(x.getName()).equals(checkNull(c.getName()))
                                    && checkNull(x.getContact()).equals(checkNull(c.getContact()))
                                    && checkNull(x.getPhone()).equals(checkNull(c.getPhone())) && checkNull(x.getMail()).equals(checkNull(c.getMail()))).count();

                            if (_theClientCount == 0) {
                                _isLitigantChanged = true;
                            }
                        }
                    } else {
                        _isLitigantChanged = true;
                    }
                } else {
                    if (_litigants != null && _litigants.size() > 0) {
                        _isLitigantChanged = true;
                    }
                }
                if (_isClientChanged) {
                    String _content = String.format("%s编辑了委托人", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                if (_isLitigantChanged) {
                    String _content = String.format("%s编辑了对方当事人", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }


                Optional<CrmProjectInfo> _theStageInfo = _projectInfos.stream().filter(x -> x.getStageid() == _stageid).findFirst();
                if (_theStageInfo.isPresent()) {

                    CrmProjectInfo _info = _theStageInfo.get();
                    ProjectInfo _requestInfo = _stage.getInfo();
                    if (!_info.getCauseofaction().equals(_requestInfo.getCauseofaction())) {
                        String _content = String.format("%s编辑了案由", _userName);
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }

                    if (!_info.getCourt().equals(_requestInfo.getCourt())) {
                        String _content = String.format("%s编辑了审理法院", _userName);
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }

                    //本诉请求
                    if (!_info.getClaim().equals(_requestInfo.getClaim())) {
                        String _content = String.format("%s编辑了本诉请求", _userName);
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }
                }

                //合议庭,书记员
                boolean _isFullCourtChanged = false;
                List<ProjectContact> _theRequestFullCourt = _stage.getInfo().getFullcourt();
                List<CrmProjectContact> _theSavedFullCourt = _projectContactList.stream().filter(x -> x.getRectype() == BaseEnum.ContactType.FullCount.getContactType()).collect(Collectors.toList());
                if (_theRequestFullCourt != null && _theRequestFullCourt.size() > 0) {
                    if (_theSavedFullCourt != null && _theSavedFullCourt.size() > 0) {
                        for (ProjectContact c : _theRequestFullCourt) {
                            long _theFullCourtCount = _theSavedFullCourt.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                            if (_theFullCourtCount == 0) {
                                _isFullCourtChanged = true;
                            }
                        }
                    } else {
                        _isFullCourtChanged = true;
                    }
                } else {
                    if (_theSavedFullCourt != null && _theSavedFullCourt.size() > 0) {
                        _isFullCourtChanged = true;
                    }
                }

                if (_theSavedFullCourt != null && _theSavedFullCourt.size() > 0) {
                    if (_theRequestFullCourt != null && _theRequestFullCourt.size() > 0) {

                        for (CrmProjectContact c : _theSavedFullCourt) {
                            long _theFullCourtCount = _theRequestFullCourt.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                            if (_theFullCourtCount == 0) {
                                _isFullCourtChanged = true;
                            }
                        }
                    } else {
                        _isFullCourtChanged = true;
                    }
                } else {

                    if (_theRequestFullCourt != null && _theRequestFullCourt.size() > 0) {
                        _isFullCourtChanged = true;
                    }
                }


                boolean _isClerkChanged = false;
                List<ProjectContact> _theRequestClerk = _stage.getInfo().getClerk();
                List<CrmProjectContact> _theSavedClerk = _projectContactList.stream().filter(x -> x.getRectype() == BaseEnum.ContactType.Clerk.getContactType()).collect(Collectors.toList());
                if (_theRequestClerk != null && _theRequestClerk.size() > 0) {
                    if (_theSavedClerk != null && _theSavedClerk.size() > 0) {
                        for (ProjectContact c : _theRequestClerk) {
                            long _theFullCourtCount = _theSavedClerk.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                            if (_theFullCourtCount == 0) {
                                _isClerkChanged = true;
                            }
                        }
                    } else {
                        _isClerkChanged = true;
                    }
                } else {
                    if (_theSavedClerk != null && _theSavedClerk.size() > 0) {
                        _isClerkChanged = true;
                    } else {
                        _isClerkChanged = false;
                    }
                }


                if (_theSavedClerk != null && _theSavedClerk.size() > 0) {
                    if (_theRequestClerk != null && _theRequestClerk.size() > 0) {
                        for (CrmProjectContact c : _theSavedClerk) {
                            long _theFullCourtCount = _theRequestClerk.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                            if (_theFullCourtCount == 0) {
                                _isClerkChanged = true;
                            }
                        }
                    } else {
                        _isClerkChanged = true;
                    }
                } else {

                    if (_theRequestClerk != null && _theRequestClerk.size() > 0) {
                        _isClerkChanged = true;
                    }
                }


                if (_isFullCourtChanged) {
                    String _content = String.format("%s编辑了合议庭", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                if (_isClerkChanged) {
                    String _content = String.format("%s编辑了书记员", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }


                //我的备注
                boolean _isRemarkChanged = false;
                List<CrmProjectRemark> _theStageRemarks = _remarks.stream().filter(x -> x.getStageid() == _stageid && x.getReccreator() == userId).collect(Collectors.toList());
                List<ProjectRemark> _theRequestRemarks = _stage.getInfo().getRemarks();
                List<CrmProjectInfoRemarkViewer> _theStageViewer = _viewers.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());


                if (_theStageRemarks == null || _theStageRemarks.size() == 0) {
                    if (_theRequestRemarks != null && _theRequestRemarks.size() > 0) {
                        for (ProjectRemark r : _theRequestRemarks) {
                            if (r.getContent() != null && !r.getContent().isEmpty()) {
                                _isRemarkChanged = true;
                                break;
                            }
                        }
                    }
                } else {
                    if (_theRequestRemarks == null || _theRequestRemarks.size() == 0) {
                        _isRemarkChanged = true;
                    } else {
                        if (_theStageRemarks.get(0).getContent() != null && !_theStageRemarks.get(0).getContent().equals(_theRequestRemarks.get(0).getContent())) {
                            _isRemarkChanged = true;
                        } else {


                        }
                    }
                }


                if (_theRequestRemarks != null && _theRequestRemarks.size() > 0) {
                    for (ProjectRemark r : _theRequestRemarks) {
                        if (r.getContent() == null) {
                            continue;
                        }
                        long _theRemarkCount = _theStageRemarks.stream().filter(x -> x.getContent() != null && x.getContent().equals(r.getContent())).count();
                        if (_theRemarkCount == 0) {
                            _isRemarkChanged = true;
                        } else {
                            List<ProjectInfoRemarkViewer> _theViewer = r.getViewer();
                            List<CrmProjectInfoRemarkViewer> _theRemarkViewer = _theStageViewer.stream().filter(x -> x.getRemarkid().equals(r.getRecid())).collect(Collectors.toList());
                            if (_theViewer != null && _theViewer.size() > 0) {
                                if (_theRemarkViewer != null && _theRemarkViewer.size() > 0) {
                                    for (ProjectInfoRemarkViewer v : _theViewer) {
                                        long _theViewerCount = _theRemarkViewer.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                                        if (_theViewerCount == 0) {
                                            _isRemarkChanged = true;
                                        }
                                    }
                                } else {
                                    _isRemarkChanged = true;
                                }
                            } else {
                                if (_theRemarkViewer != null && _theRemarkViewer.size() > 0) {
                                    _isRemarkChanged = true;
                                }
                            }

                            if (_theRemarkViewer != null && _theRemarkViewer.size() > 0) {
                                if (_theViewer != null && _theViewer.size() > 0) {
                                    for (CrmProjectInfoRemarkViewer v : _theRemarkViewer) {
                                        long _theViewerCount = _theViewer.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                                        if (_theViewerCount == 0) {
                                            _isRemarkChanged = true;
                                        }
                                    }
                                } else {
                                    _isRemarkChanged = true;
                                }
                            } else {
                                if (_theViewer != null && _theViewer.size() > 0) {
                                    _isRemarkChanged = true;
                                }
                            }
                        }
                    }
                } else {
                    if (_theStageRemarks != null && _theStageRemarks.size() > 0) {
                        _isRemarkChanged = true;
                    }
                }


                if (_theStageRemarks != null && _theStageRemarks.size() > 0) {
                    if (_theRequestRemarks != null && _theRequestRemarks.size() > 0) {
                        for (CrmProjectRemark r : _theStageRemarks) {
                            long _theRemarkCount = _theRequestRemarks.stream().filter(x -> x.getRecid().equals(r.getRecid())).count();
                            if (_theRemarkCount == 0) {
                                _isRemarkChanged = true;
                            } else {

                                List<CrmProjectInfoRemarkViewer> _theRemarkViewer = _theStageViewer.stream().filter(x -> x.getRemarkid().equals(r.getRecid())).collect(Collectors.toList());
                                Optional<ProjectRemark> _theRequestRemark = _theRequestRemarks.stream().filter(x -> x.getRecid().equals(r.getRecid())).findFirst();
                                if (_theRequestRemark.isPresent()) {
                                    List<ProjectInfoRemarkViewer> _theViewer = _theRequestRemark.get().getViewer();
                                    if (_theRemarkViewer != null && _theViewer != null) {
                                        for (CrmProjectInfoRemarkViewer v : _theRemarkViewer) {
                                            long _theViewerCount = _theViewer.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                                            if (_theViewerCount == 0) {
                                                _isRemarkChanged = true;
                                            }
                                        }

                                        for (CrmProjectInfoRemarkViewer v : _theRemarkViewer) {
                                            long _theViewerCount = _theViewer.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                                            if (_theViewerCount == 0) {
                                                _isRemarkChanged = true;
                                            }
                                        }
                                    }
                                    if (_theRemarkViewer == null || _theRemarkViewer.size() == 0) {
                                        if (_theViewer != null && _theViewer.size() > 0) {
                                            _isRemarkChanged = true;
                                        }
                                    }

                                    if (_theViewer == null || _theViewer.size() == 0) {
                                        if (_theRemarkViewer != null && _theRemarkViewer.size() > 0) {
                                            _isRemarkChanged = true;
                                        }
                                    }
                                } else {
                                    _isRemarkChanged = true;
                                }
                            }
                        }
                    }
                }

                if (_isRemarkChanged) {
                    String _content = String.format("%s编辑了备注", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }


                //check tasks
                boolean _isTaskChanged = false;
                List<ProjectTask> _stageRequestTasks = _stage.getTasks();
                if (_stageRequestTasks != null && _stageRequestTasks.size() > 0) {
                    if (_tasks != null && _tasks.size() > 0) {
                        for (ProjectTask t : _stageRequestTasks) {
                            long _theTaskCount = _tasks.stream().filter(x -> x.getTaskid().equals(t.getRecid())).count();
                            if (_theTaskCount == 0) {
                                _isTaskChanged = true;
                                String _content = String.format("%s创建了任务%s", _userName, checkNull(t.getTaskcontent()));
                                _messageContent.add(_content);
                                Map<String, String> cMap = new HashMap<>();
                                cMap.put("content", _content);
                                cMap.put("pushType", "0");
                                contentList.add(cMap);
                            }
                        }
                    } else {
                        _isTaskChanged = true;
                        for (ProjectTask t : _stageRequestTasks) {
                            String _content = String.format("%s创建了任务%s", _userName, checkNull(t.getTaskcontent()));
                            _messageContent.add(_content);
                            Map<String, String> cMap = new HashMap<>();
                            cMap.put("content", _content);
                            cMap.put("pushType", "0");
                            contentList.add(cMap);
                        }
                    }
                }

                if (_tasks != null && _tasks.size() > 0) {
                    if (_stageRequestTasks != null && _stageRequestTasks.size() > 0) {
                        for (CrmProjectTask t : _tasks) {
                            long _theTaskCount = _stageRequestTasks.stream().filter(x -> x.getTaskid().equals(t.getRecid())).count();
                            if (_theTaskCount == 0) {
                                _isTaskChanged = true;
                                String _content = String.format("%s删除了任务%s", _userName, checkNull(t.getTaskcontent()));
                                _messageContent.add(_content);
                                Map<String, String> cMap = new HashMap<>();
                                cMap.put("content", _content);
                                cMap.put("pushType", "0");
                                contentList.add(cMap);
                            }
                        }
                    } else {
                        _isTaskChanged = true;
                        for (CrmProjectTask t : _tasks) {
                            String _content = String.format("%s删除了任务%s", _userName, checkNull(t.getTaskcontent()));
                            _messageContent.add(_content);
                            Map<String, String> cMap = new HashMap<>();
                            cMap.put("content", _content);
                            cMap.put("pushType", "0");
                            contentList.add(cMap);
                        }
                    }
                }


                //get groupids

                List<String> _theGroupIds = new ArrayList<>();
                if (_chatGroups != null) {
                    List<CrmChatGroupPart> _stageChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == _stageid
                            && x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).collect(Collectors.toList());
                    if (_stageChatGroups != null) {
                        for (CrmChatGroupPart g : _stageChatGroups) {
                            _theGroupIds.add(g.getGroupid());
                        }
                    }

                    List<CrmProjectClient> _theSavedClients = getProjectClient(_projectid);
                    Optional<CrmProjectClient> _theOnlyClient = _theSavedClients.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.Client.getPersonType()
                            && x.getStageid() == _stageid).findFirst();

                    String _theClientId = _theOnlyClient.get().getRecid();

                    Optional<CrmChatGroupPart> _stageClientChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == _stageid
                            && x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType() && x.getRelatedid().equals(_theClientId)).findFirst();

                    if (_stageClientChatGroups.isPresent()) {
                        _theGroupIds.add(_stageClientChatGroups.get().getGroupid());
                    }

                }


                logger.info("begin send message");
                logger.info("group size:" + _theGroupIds.size());
                logger.info("message content size:" + _messageContent.size());
                /*if (_messageContent != null && _messageContent.size() > 0 && _theGroupIds != null && _theGroupIds.size() > 0) {
                    for (String _message : _messageContent) {
                        if (!_message.isEmpty()) {
                            sendIMMessage(_theGroupIds, _message, userId);
                        }
                    }

                }*/
                if (contentList != null && contentList.size() > 0 && _theGroupIds != null && _theGroupIds.size() > 0) {
                    for (Map<String, String> stringMap : contentList) {
                        if (!stringMap.get("content").isEmpty() && !stringMap.get("pushType").isEmpty()) {
                            sendIMMessage(_theGroupIds, stringMap.get("content"), userId, Integer.parseInt(stringMap.get("pushType")));
                        }
                    }
                }
                logger.info("end send message");

            } catch (Exception ex) {
                String _errorMessage = ex.getMessage();
                logger.info("send message error:" + _errorMessage);
                ex.printStackTrace();
            }
        }
        map.put("result", result);
        return map;
    }

    //详情
    public ProjectDetailResponse getProjectDeail(String id, int userid, String device) {
        ProjectDetailResponse _detailResponse = new ProjectDetailResponse();
        try {

            //获取项目主数据
            boolean _isProjectCompleted = false;
            int _theProjectType = 0;
            List<CrmProject> _projectList = getProject(id);
            if (_projectList != null && _projectList.size() > 0) {
                CrmProject _project = _projectList.get(0);
                //_detailResponse.set(_project.getRecid());
                _detailResponse.setName(_project.getRecname());
                _detailResponse.setProjecttype(_project.getProjecttype());

                if (_project.getProjectstatus() == BaseEnum.ProjectStatusType.Complete.getProjectStatusType()) {
                    _isProjectCompleted = true;
                } else {
                    _isProjectCompleted = false;
                }
                _detailResponse.setIscomplete(_isProjectCompleted);

                _theProjectType = _project.getProjecttype();
            }


            //项目阶段
            List<CrmProjectStage> _stageList = getProjectStageList(id);
            System.out.println("stages size:" + _stageList.size());

            List<CommonItem> _stagesResponse = new ArrayList<>();
            for (CrmProjectStage _stage : _stageList) {
                CommonItem _item = new CommonItem();
                _item.setRecid(_stage.getStageid());
                _item.setRecname(_stage.getStagename());
                _item.setRecorder(_stage.getOrder());
                if (_stage.getStagetype() == BaseEnum.StageType.Define.getStageType()) {
                    _item.setIsuserdefine(true);
                } else {
                    _item.setIsuserdefine(false);
                }
                _stagesResponse.add(_item);
            }


            _detailResponse.setStages(_stagesResponse);

            //委托人和对方当事人
            List<CrmProjectClient> _clientList = getProjectClient(id);

            //信息
            List<CrmProjectInfo> _infoList = getProjectInfo(id);

            //合议庭，书记员
            List<CrmProjectContact> _contactList = getProjectContact(id, userid);

            //获取备注
            //how to handle permision
            List<CrmProjectRemark> _remarks = getProjectRemark(id, userid);

            //获取可以看到备注的人
            List<CrmProjectInfoRemarkViewer> _viewers = getProjectRemarkViewer(id, userid);

            //文件资料
            List<CrmProjectFile> _fileList = getProjectFiles(id, userid);

            //团队成员
            List<CrmProjectMember> _memberList = getProjectMember(id, userid);
            List<CrmProjectMember> _tmpMemberList = _memberList.stream().filter(x -> x.getUserid() == userid).collect(Collectors.toList());
            if (_tmpMemberList != null && _tmpMemberList.size() > 0) {
                List<CrmProjectMember> _managerMembers = _tmpMemberList.stream().filter(x -> x.getIsmanager()).collect(Collectors.toList());
                if (_managerMembers != null && _managerMembers.size() > 0) {
                    _detailResponse.setIsmanager(true);
                }
                List<CrmProjectMember> _hostMembers = _tmpMemberList.stream().filter(x -> x.ishost()).collect(Collectors.toList());
                if (_hostMembers != null && _hostMembers.size() > 0) {
                    _detailResponse.setIshost(true);
                }
            }


            int _lawerGroupType = BaseEnum.GroupType.Lawyer.getGroupType();
            int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
            int _innerClientGroup = BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType();
            int _innerLawyerGroup = BaseEnum.InnerGroupType.LawyerGroup.getInnerGroupType();

            long _allLawyerManagerCount = _tmpMemberList.stream().filter(x -> x.getGrouptype() == _lawerGroupType && x.getIsmanager()).count();
            long _allLawyerHostrCount = _tmpMemberList.stream().filter(x -> x.getGrouptype() == _lawerGroupType && x.ishost()).count();

            long _allInnerClientManagerCount = _tmpMemberList.stream().filter(x -> x.getGrouptype() == _clientGroupType
                    && x.getInnergrouptype() == _innerClientGroup
                    && x.getIsmanager()).count();

            long _allInnerLawyerManagerCount = _tmpMemberList.stream().filter(x -> x.getGrouptype() == _clientGroupType
                    && x.getInnergrouptype() == _innerLawyerGroup
                    && x.getIsmanager() == true).count();

            long _allInnerLawyerHostCount = _tmpMemberList.stream().filter(x -> x.getGrouptype() == _clientGroupType
                    && x.getInnergrouptype() == _innerLawyerGroup
                    && x.ishost() == true).count();


            if (_allLawyerManagerCount > 0) {
                _detailResponse.setIslawyermanager(true);
            } else {
                _detailResponse.setIslawyermanager(false);
            }

            if (_allLawyerHostrCount > 0) {
                _detailResponse.setIslawyerhost(true);
            } else {
                _detailResponse.setIslawyerhost(false);
            }


            if (_allInnerClientManagerCount > 0) {
                _detailResponse.setIsclientmanager(true);
            } else {
                _detailResponse.setIsclientmanager(false);
            }

            if (_allInnerLawyerManagerCount > 0) {
                _detailResponse.setIsclientlawyermanager(true);
            } else {
                _detailResponse.setIsclientlawyermanager(false);
            }

            if (_allInnerLawyerHostCount > 0) {
                _detailResponse.setIsclientlawyerhost(true);
            } else {
                _detailResponse.setIsclientlawyerhost(false);
            }

            List<ProjectStage> _stageResponse = new ArrayList<>();
            int _clientPersonType = BaseEnum.PersonType.Client.getPersonType();
            int _litigantPersonType = BaseEnum.PersonType.litigant.getPersonType();
            int _fullcourtType = BaseEnum.ContactType.FullCount.getContactType();
            int _clerkType = BaseEnum.ContactType.Clerk.getContactType();

            //获取项目任务
            List<CrmProjectTask> _taskList = getProjectTask(id);
            List<ProjectTask> _tasks = new ArrayList<>();
            for (CrmProjectTask task : _taskList) {
                ProjectTask _task = toProjectTask(task);
                _tasks.add(_task);
            }

            //获取 stage relate
            List<CrmProjectStageRelate> _oldStageRelates = getProjectStageRelate(id);

            //get project folder 获取当前项目的所有文件夹
            List<CrmProjectFolder> _folders = getProjectFolder(id, userid);
            //过滤出公共文件夹folderType = 1
            List<CrmProjectFolder> _projectFolders = _folders.stream().filter(x -> x.getFoldertype() == BaseEnum.ProjectFolderType.Common.getProjectFolderType()).collect(Collectors.toList());

            for (CrmProjectStage _stage : _stageList) {

                List<ProjectClient> _responseClient = new ArrayList<>();
                List<ProjectClient> _responseLitigant = new ArrayList<>();

                //项目阶段id
                int _stateid = _stage.getStageid();
                ProjectStage _responseStage = new ProjectStage();
                ProjectInfo _projectInfo = new ProjectInfo();
                _responseStage.setInfo(_projectInfo);
                _responseStage.setStageid(_stateid);
                _responseStage.setStageorder(_stage.getOrder());
                if (_stage.getStagetype() == BaseEnum.StageType.Define.getStageType()) {
                    _responseStage.setIsuserdefine(true);
                } else {
                    _responseStage.setIsuserdefine(false);
                }

                //项目是否已经完成
                Optional<CrmProjectStageRelate> _theStageRelate = _oldStageRelates.stream().filter(x -> x.getStageid() == _stateid).findFirst();
                if (_theStageRelate.isPresent()) {
                    int _theStageStatus = _theStageRelate.get().getStagestatus();
                    if (_theStageStatus == BaseEnum.ProjectStageStatus.Complete.getProjectStageStatus()) {
                        _responseStage.setIscomplete(true);
                    } else {
                        _responseStage.setIscomplete(false);
                    }
                }

                //阶段成员
                List<CrmProjectMember> _stageMembers = _memberList.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());

                //委托人
                List<CrmProjectClient> _tmpClientList = _clientList.stream().filter(x -> x.getStageid() == _stateid
                        && x.getPersontype() == _clientPersonType).collect(Collectors.toList());

                for (CrmProjectClient _client : _tmpClientList) {
                    List<CrmProjectMember> _tmpMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).collect(Collectors.toList());
                    // _stageMembers.stream().filter(x -> x.getRelatedid() != null
                    //&& x.getRelatedid().equals(_client.getRecid())).collect(Collectors.toList());

                    List<ProjectMember> _responseMembers = toProjectMemberList(_tmpMembers);
                    for (ProjectMember _m : _responseMembers) {
                        _m.setClientid(_client.getRecid());

                        _m.setHeadimage("");
                        int _userid = _m.getUserid();
                        CrmUserPart _theUserPart = _commonRepository.getUserInfoALL(_userid);
                        if (_theUserPart != null) {
                            String _theHeadImage = _theUserPart.getHeadimage();
                            _m.setHeadimage(_theHeadImage);
                        }
                    }

                    ProjectClient _c = toProjectClient(_client);
                    _c.setMembers(_responseMembers);
                    _responseClient.add(_c);
                }
                _responseStage.getInfo().setClient(_responseClient);


                //对方当事人
                List<CrmProjectClient> _tmpLitigantList = _clientList.stream().filter(x -> x.getStageid() == _stateid
                        && x.getPersontype() == _litigantPersonType).collect(Collectors.toList());
                for (CrmProjectClient _client : _tmpLitigantList) {
                    _responseLitigant.add(toProjectClient(_client));
                }
                _responseStage.getInfo().setLitigant(_responseLitigant);


                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                //基本信息
                for (CrmProjectInfo _info : _infoList) {
                    if (_info.getStageid() == _stateid) {
                        _responseStage.getInfo().setCauseofaction(_info.getCauseofaction());
                        _responseStage.getInfo().setCourt(_info.getCourt());
                        _responseStage.getInfo().setCasenumber(_info.getCasenumber());
                        _responseStage.getInfo().setClaim(_info.getClaim());
                        //  _responseStage.setRemark(_info.getRemark());

                        _responseStage.getInfo().setCivilrequest(_info.getCivilrequest());
                        _responseStage.getInfo().setCrimename(_info.getCrimename());

                        if (_info.getDetentiondate() != null) {
                            String _strDetentiondate = df.format(_info.getDetentiondate());
                            _responseStage.getInfo().setDetentiondate(_strDetentiondate);
                        } else {
                            _responseStage.getInfo().setDetentiondate("");
                        }

                        if (_info.getArrestdate() != null) {
                            String _stArrestdate = df.format(_info.getArrestdate());
                            _responseStage.getInfo().setArrestdate(_stArrestdate);
                        } else {
                            _responseStage.getInfo().setArrestdate("");
                        }
                        _responseStage.getInfo().setCustodyplace(_info.getCustodyplace());

                    }
                }

                //过滤
                List<ProjectContact> _fullcourtResponse = new ArrayList<>();
                List<ProjectContact> _clerkResponse = new ArrayList<>();
                for (CrmProjectContact _contact : _contactList) {
                    if (_contact.getStageid() == _stateid) {
                        ProjectContact _pc = toProjectContract(_contact);
                        if (_contact.getRectype() == _fullcourtType) {
                            _fullcourtResponse.add(_pc);
                        } else if (_contact.getRectype() == _clerkType) {
                            _clerkResponse.add(_pc);
                        }
                    }
                }

                //合议庭
                _responseStage.getInfo().setFullcourt(_fullcourtResponse);

                //书记员
                _responseStage.getInfo().setClerk(_clerkResponse);

                //备注
                List<ProjectRemark> _newProjectRemarks = new ArrayList<>();
                List<CrmProjectRemark> _currentRemarkList = _remarks.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());
                for (CrmProjectRemark _remark : _currentRemarkList) {
                    List<CrmProjectInfoRemarkViewer> _tmpViewer = _viewers.stream().filter(x -> x.getRemarkid().equals(_remark.getRecid())).collect(Collectors.toList());
                    List<ProjectInfoRemarkViewer> _tmpList = toProjectInfoRemarkViewers(_tmpViewer);
                    ProjectRemark _tmpRemark = toProjectRemark(_remark);
                    _tmpRemark.setViewer(_tmpList);

                    //只能查看我自己的和分享给我的备注
                    long _tmpCount = _tmpViewer.stream().filter(x -> x.getUserid() == userid).count();
                    if (_remark.getReccreator() == userid || _tmpCount > 0) {
                        _newProjectRemarks.add(_tmpRemark);
                    }
                }
                _responseStage.getInfo().setRemarks(_newProjectRemarks);


                //文件资料
                List<CrmProjectFile> _stageFiles = _fileList.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());
                //当前阶段的文件资料
                List<ProjectFile> _fileReponse = new ArrayList<>();
                for (CrmProjectFile _file : _fileList) {
                    if (_file.getStageid() == _stateid) {
                        ProjectFile file = toProjectFile(_file);
                        _fileReponse.add(file);
                    }
                }

                //判断登陆用户是否是律师协作团队成员
                boolean _userInLaywerMember = false;
                List<CrmProjectMember> _lawerMemberTmp = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType() && x.getUserid() == userid).collect(Collectors.toList());
                if (_lawerMemberTmp != null && _lawerMemberTmp.size() > 0) {
                    _userInLaywerMember = true;
                }

                //获取拥有权限的文件夹
                List<String> _folderids = new ArrayList<>();
                List<CrmProjectFolder> folderList = new ArrayList<>();
                //获取当前阶段的所有文件夹
                List<CrmProjectFolder> _stageFolders = _folders.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());
                //登录用户不是律师协作团队成员
                if (!_userInLaywerMember) {
/*
                    //可以看到的委托人文件夹
                    for (CrmProjectClient _c : _tmpClientList) {
                        List<CrmProjectFolder> _tmpFolders = _stageFolders.stream().filter(x -> x.getRelatedid() != null && x.getRelatedid().equals(_c.getRecid())).collect(Collectors.toList());
                        if (_tmpFolders != null && _tmpFolders.size() > 0) {
                            List<String> _tmpIds = _tmpFolders.stream().map(CrmProjectFolder::getRecid).collect(Collectors.toList());
                            _folderids.addAll(_tmpIds);
                        }
                    }
                    //可以看到对方当事人的文件夹

                    //项目文件夹

                    //阶段文件夹

                    //可以看到的自定义文件夹
                    List<CrmProjectFolder> _userDefineFolders = _stageFolders.stream().filter(x -> x.getFoldertype() == BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType() && !x.islawyerfolder()).collect(Collectors.toList());
                    List<String> _userDefineFolderIds = _userDefineFolders.stream().map(CrmProjectFolder::getRecid).distinct().collect(Collectors.toList());
                    _folderids.addAll(_userDefineFolderIds);
*/

                    for (CrmProjectFolder _f : _stageFolders) {
                        if (_f.getFoldertype() == BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType() && _f.islawyerfolder()) {
                            continue;
                        } else if (_f.getFoldertype() == BaseEnum.ProjectFolderType.Stage.getProjectFolderType() && _f.islawyerfolder()) {
                            continue;
                        } else {
                            _folderids.add(_f.getRecid());
                            folderList.add(_f);
                        }
                    }
                    //添加项目的公共文件夹id
                    for (CrmProjectFolder f : _projectFolders) {
                        _folderids.add(f.getRecid());
                        folderList.add(f);
                    }
                } else {
                    //登录用户是律师协作团队成员
                    //所有文件资料的 所属文件夹id
                    _folderids = _fileReponse.stream().map(ProjectFile::getFolderid).distinct().collect(Collectors.toList());
                    //TODO: 2022/6/22  显示空文件夹问题 start
                    //所有文件夹id,  包含有文件的没有文件的
                    folderList = _folders;
                    //显示空文件夹问题 end
                }

                //把文件归属给文件夹
                List<ProjectFileFolder> _files = new ArrayList<>();
                List<String> _theFileFolders = _fileReponse.stream().map(ProjectFile::getFolderid).collect(Collectors.toList());
                _theFileFolders = _theFileFolders.stream().distinct().collect(Collectors.toList());

                //判断不同的客户端
                if (StringUtils.hasText(device) && device.equals("WEB")) {
                    // TODO: 2022/6/22  把文件归属给文件夹 显示空文件夹问题 start
                    for (CrmProjectFolder folder : folderList) {
                        ProjectFileFolder f = new ProjectFileFolder();
                        f.setFolderid(folder.getRecid());
                        f.setFoldertype(folder.getFoldertype());
                        f.setFoldername(folder.getPrefixname() + folder.getRecname());
                        f.setIsclientfolder(!folder.islawyerfolder());
                        f.setClientid(folder.getRelatedid());
                        f.setIsuserdefinefolder(folder.getFoldertype() == BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType());
                        f.setInnerfoldertype(folder.getInnerfoldertype());
                        List<ProjectFile> tmpItems = _fileReponse.stream().filter(x ->x.getFolderid()!=null&&x.getFolderid().equals(folder.getRecid())).collect(Collectors.toList());
                        f.setItems(tmpItems);
                        _files.add(f);
                    }
                    //显示空文件夹问题 end
                } else {

                    if (_theFileFolders != null && _theFileFolders.size() > 0) {
                        for (String _folderid : _theFileFolders) {
                            if (_folderids.contains(_folderid)) {
                                List<CrmProjectFolder> _theTmpFolders = _folders.stream().filter(x -> x.getRecid().equals(_folderid)).collect(Collectors.toList());
                                String _folderName = "";
                                CrmProjectFolder _currentFolder = null;
                                boolean _isClientFolder = false;
                                boolean _isUserDefineFolder = false;
                                if (_theTmpFolders != null && _theTmpFolders.size() > 0) {
                                    _currentFolder = _theTmpFolders.get(0);
                                    _folderName = _currentFolder.getPrefixname() + _currentFolder.getRecname();
                                    _isClientFolder = !_currentFolder.islawyerfolder();
                                    if (_currentFolder.getFoldertype() == BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType()) {
                                        _isUserDefineFolder = true;
                                    }
                                }
                                //如果有文件，就添加到列表中来
                                List<ProjectFile> _tmpItems = _fileReponse.stream().filter(x -> x.getFolderid()!=null&&x.getFolderid().equals(_folderid)).collect(Collectors.toList());

                                if (_tmpItems != null && _tmpItems.size() > 0) {
                                    ProjectFileFolder _f = new ProjectFileFolder();
                                    _f.setFolderid(_folderid);
                                    _f.setFoldername(_folderName);
                                    _f.setIsclientfolder(_isClientFolder);
                                    _f.setIsuserdefinefolder(_isUserDefineFolder);

                                    if (_currentFolder != null) {
                                        _f.setClientid(_currentFolder.getRelatedid());
                                        _f.setFoldertype(_currentFolder.getFoldertype());
                                        _f.setInnerfoldertype(_currentFolder.getInnerfoldertype());
                                    } else {
                                        _f.setClientid("");
                                        _f.setFoldertype(0);
                                        _f.setInnerfoldertype(0);
                                    }
                                    _f.setItems(_tmpItems);
                                    _files.add(_f);
                                }
                            }
                        }
                    }
                }


//                _files.sort(Comparator.comparing(ProjectFileFolder::getIsclientfolder));
                _files.sort(Comparator.comparing(x -> x.getItems().size(), Comparator.reverseOrder()));


                // _files.sort(Comparator.comparing(ProjectFileFolder::getFoldertype));

                /*Collections.sort(_files, new FolderComparator());

                List<ProjectFileFolder> _filesTmp = new ArrayList<>();
                List<ProjectFileFolder> _filesTmp2 = new ArrayList<>();
                List<ProjectFileFolder> _filesTmp3 = new ArrayList<>();
                for (ProjectFileFolder _theFolder : _files) {
                    if (_theFolder.getFoldertype() == 0 || _theFolder.getFoldertype() == 1) {
                        _filesTmp.add(_theFolder);
                    } else {
                        _filesTmp2.add(_theFolder);
                    }
                }

                for (ProjectFileFolder _theFolder2 : _filesTmp2) {
                    if (_theFolder2.getFoldertype() == 4 || !_theFolder2.getIsclientfolder()) {
                        _filesTmp.add(_theFolder2);
                    } else {
                        _filesTmp3.add(_theFolder2);
                    }
                }
                for (ProjectFileFolder _theFolder3 : _filesTmp3) {
                    _filesTmp.add(_theFolder3);

                }*/


                // _responseStage.setFiles(_filesTmp);
                _responseStage.setFiles(_files);

                //设置任务
                //如果登陆账号是任务成员，可以查看任务详情
                List<ProjectTask> _currentTask = _tasks.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());
                List<ProjectTask> _theClientTask = new ArrayList<>();

                //委托人协作团队成员不允许看到律师协作团队的成员任务
                long _theUserCount = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType() && x.getUserid() == userid).count();
                //非律师协作团队成员
                if (_theUserCount == 0) {
                    List<CrmProjectMember> _theStageClientMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).collect(Collectors.toList());
                    List<CrmProjectMember> _theStageLawyerMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()).collect(Collectors.toList());
                    List<CrmProjectMember> _onlyClientMembers = new ArrayList<>();

                    for (CrmProjectMember m : _theStageClientMembers) {
                        long _theCount = _theStageLawyerMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                        if (_theCount == 0) {
                            _onlyClientMembers.add(m);
                        }
                    }

                    for (ProjectTask t : _currentTask) {
                        //long _theCount = _onlyClientMembers.stream().filter(x -> x.getUserid() == t.getTaskcreator()).count();
                        List<CrmTaskMember> _theTaskMembers = getTaskMember(t.getTaskid());
                        boolean _isTaskMember = false;
                        for (CrmProjectMember m : _onlyClientMembers) {

                            long _theCount = _theTaskMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                            if (_theCount > 0) {
                                _isTaskMember = true;
                                break;
                            }
                        }

                        if (_isTaskMember) {
                            _theClientTask.add(t);
                        }
                    }
                    _currentTask = _theClientTask;
                }


                for (ProjectTask t : _currentTask) {
                    t.setIsclientvisible(false);
                    t.setOwnfile(false);

                    List<CrmTaskFile> _taskFiles = _commonRepository.getTaskFiles(t.getTaskid());
                    if (_taskFiles != null && _taskFiles.size() > 0) {
                        t.setOwnfile(true);
                    }


                    List<CrmProjectMember> _clientProjectMembers = _memberList.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()
                            && x.getStageid() == _stateid).collect(Collectors.toList());
                    List<CrmProjectMember> _lawyerProjectMembers = _memberList.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()
                            && x.getStageid() == _stateid).collect(Collectors.toList());
                    List<CrmProjectMember> _tmpCompareMembers = new ArrayList<>();
                    for (CrmProjectMember m : _clientProjectMembers) {
                        long _theCount = _lawyerProjectMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                        if (_theCount == 0) {
                            _tmpCompareMembers.add(m);
                        }
                    }


                    List<CrmTaskMember> _taskMembers = getTaskMember(t.getTaskid());
                    List<CrmTaskMember> _tmpMembers = _taskMembers.stream().filter(x -> x.getUserid() == userid).collect(Collectors.toList());
                    if (_tmpMembers != null && _tmpMembers.size() > 0) {
                        t.setIsclick(true);
                    } else {
                        t.setIsclick(false);
                    }

                    if (_tmpCompareMembers != null && _tmpCompareMembers.size() > 0) {
                        for (CrmProjectMember m : _tmpCompareMembers) {
                            long _theTaskMemberCount = _taskMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                            if (_theTaskMemberCount > 0) {
                                t.setIsclientvisible(true);
                                break;
                            }
                        }
                    }


                    List<CrmTaskMember> _tmpHostMembers = _taskMembers.stream().filter(x -> x.ishost() && x.getUserid() == userid).collect(Collectors.toList());
                    if (_tmpHostMembers != null && _tmpHostMembers.size() > 0) {
                        t.setIshost(true);
                    } else {
                        t.setIshost(false);
                    }
                }


                _responseStage.setTasks(_currentTask);

                //设置律师协作团队成员
                List<CrmProjectMember> _laywerMemberes = _stageMembers.stream().filter(x -> x.getGrouptype() == _lawerGroupType).collect(Collectors.toList());
                List<ProjectMember> _laywerResonseMember = toProjectMemberList(_laywerMemberes);
                for (ProjectMember m : _laywerResonseMember) {
                    m.setHeadimage("");
                    int _userid = m.getUserid();
                    CrmUserPart _theUserPart = _commonRepository.getUserInfoALL(_userid);
                    if (_theUserPart != null) {
                        String _theHeadImage = _theUserPart.getHeadimage();
                        m.setHeadimage(_theHeadImage);
                    }
                }

                //律师协作团队的人才可以看到律师协作团队的成员
                if (_userInLaywerMember) {
                    _responseStage.setMembers(_laywerResonseMember);
                }


                long _lawyerMnagerCount = _laywerMemberes.stream().filter(x -> x.getUserid() == userid && x.getIsmanager()).count();
                long _lawyerHostCount = _laywerMemberes.stream().filter(x -> x.getUserid() == userid && x.ishost()).count();
                if (_lawyerMnagerCount > 0) {
                    _responseStage.setIslawyermanager(true);
                }
                if (_lawyerHostCount > 0) {
                    _responseStage.setIslawyerhost(true);
                }


                boolean _isInLawyerMember = false;
                long _theLawyerMemberCount = _laywerMemberes.stream().filter(x -> x.getUserid() == userid).count();
                if (_theLawyerMemberCount > 0) {
                    _isInLawyerMember = true;
                }


                long _innerClientGroupManagerCount = _stageMembers.stream().filter(x -> x.getGrouptype() == _clientGroupType
                        && x.getInnergrouptype() == _innerClientGroup
                        && x.getUserid() == userid && x.getIsmanager()).count();

                if (_innerClientGroupManagerCount > 0) {
                    _responseStage.setIsclientmanager(true);
                }

                long _innerLawyerGroupManagerCount = _stageMembers.stream().filter(x -> x.getGrouptype() == _clientGroupType
                        && x.getInnergrouptype() == _innerLawyerGroup && x.getUserid() == userid && x.getIsmanager()).count();
                if (_innerLawyerGroupManagerCount > 0) {
                    _responseStage.setIslawyermanager(true);
                }

                long _innerLawyerGroupHostCount = _stageMembers.stream().filter(x -> x.getGrouptype() == _clientGroupType
                        && x.getInnergrouptype() == _innerLawyerGroup && x.getUserid() == userid && x.ishost()).count();
                if (_innerLawyerGroupHostCount > 0) {
                    _responseStage.setIslawyerhost(true);
                }

                //
                List<CrmProjectMember> _userStageMembers = _stageMembers.stream().filter(x -> x.getUserid() == userid).collect(Collectors.toList());
                if (_userStageMembers != null && _userStageMembers.size() > 0) {

                    List<CrmProjectMember> _userStageHostMembers = _userStageMembers.stream().filter(x -> x.ishost()).collect(Collectors.toList());
                    if (_userStageHostMembers != null && _userStageHostMembers.size() > 0) {
                        _responseStage.setIshost(true);
                    } else {
                        _responseStage.setIshost(false);
                    }

                    List<CrmProjectMember> _userStageManagerMembers = _userStageMembers.stream().filter(x -> x.getIsmanager()).collect(Collectors.toList());
                    if (_userStageManagerMembers != null && _userStageManagerMembers.size() > 0) {
                        _responseStage.setIsmanager(true);
                    } else {
                        _responseStage.setIsmanager(false);
                    }
                    _responseStage.setIsmember(true);

                } else {
                    _responseStage.setIsmanager(false);
                    _responseStage.setIshost(false);
                    _responseStage.setIsmember(false);
                }

                //是否是律师协作团队，普通成员
                long _commonLawyerMember = _laywerMemberes.stream().filter(x -> x.getUserid() == userid && !x.ishost() && !x.getIsmanager()).count();
                if (_commonLawyerMember > 0) {
                    _responseStage.setIslawyermember(true);
                } else {
                    _responseStage.setIslawyermember(false);
                }

                long _commonClientMemberCount = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType() &&
                        x.getUserid() == userid
                        && !x.ishost()
                        && !x.getIsmanager()).count();
                if (_commonClientMemberCount > 0) {
                    _responseStage.setIsclientmember(true);
                } else {
                    _responseStage.setIsclientmember(false);
                }


                //todo:设置聊天组数据

                //委托人协作团队聊天组
                List<ProjectChatGroupItem> clientchatgroups = new ArrayList<>();

                //律师协作团队聊天组
                List<ProjectChatGroupItem> lawyerchatgroups = new ArrayList<>();


                List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(id);
                List<CrmChatGroupPart> _stageChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());
                if (_stage.getIscomplete()) {
                    _isProjectCompleted = true;
                }
                if (_stageChatGroups != null && _stageChatGroups.size() > 0) {
                    List<CrmChatGroupPart> _clientChatGroups = _stageChatGroups.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).collect(Collectors.toList());
                    List<CrmChatGroupPart> _lawyerChatGroups = _stageChatGroups.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).collect(Collectors.toList());

                    if (_clientChatGroups != null && _clientChatGroups.size() > 0) {
                        for (CrmChatGroupPart _c : _clientChatGroups) {
                            ProjectChatGroupItem _item = new ProjectChatGroupItem();
                            _item.setGroupid(_c.getGroupid());
                            _item.setGroupname(_c.getGroupname());
                            _item.setClientid(_c.getRelatedid());

                            _item.setCurrentchatstageid(_c.getChatstageid());
                            _item.setIscomplete(_isProjectCompleted);
                            _item.setProjectstageid(_stateid);
                            _item.setIsinlawyermember(_isInLawyerMember);
                            _item.setCurrentchatstagename("");

                            //设置聊天阶段名称
                            Optional<CrmProjectClient> _theClient = _tmpClientList.stream().filter(x -> x.getRecid().equals(_c.getRelatedid())).findFirst();
                            if (_theClient.isPresent()) {
                                String _theTitleid = _theClient.get().getTitleid();
                                if (_theTitleid != null && !_theTitleid.isEmpty()) {
                                    List<CrmChatStage> _theChatStages = _commonRepository.getChatStages(_theProjectType, _c.getGroupid(), _stateid, _theTitleid);
                                    if (_theChatStages != null && _theChatStages.size() > 0) {
                                        Optional<CrmChatStage> _chatStage = _theChatStages.stream().filter(x -> x.getStageid() == _c.getChatstageid()).findFirst();
                                        if (_chatStage.isPresent()) {
                                            _item.setCurrentchatstagename(_chatStage.get().getStagename());
                                        }
                                    }
                                }
                            }
                            clientchatgroups.add(_item);
                        }
                    }
                    _responseStage.setClientchatgroups(clientchatgroups);

                    if (_lawyerChatGroups != null && _lawyerChatGroups.size() > 0) {
                        for (CrmChatGroupPart _c : _lawyerChatGroups) {
                            ProjectChatGroupItem _item = new ProjectChatGroupItem();
                            _item.setGroupid(_c.getGroupid());
                            _item.setGroupname(_c.getGroupname());
                            _item.setClientid(_c.getRelatedid());

                            _item.setCurrentchatstageid(_c.getChatstageid());
                            _item.setIscomplete(_isProjectCompleted);
                            _item.setProjectstageid(_stateid);
                            _item.setIsinlawyermember(_isInLawyerMember);
                            _item.setCurrentchatstagename("");

                            //设置聊天阶段名称
                            Optional<CrmProjectClient> _theClient = _tmpClientList.stream().filter(x -> x.getRecid().equals(_c.getRelatedid())).findFirst();
                            if (_theClient.isPresent()) {
                                String _theTitleid = _theClient.get().getTitleid();
                                if (_theTitleid != null && !_theTitleid.isEmpty()) {
                                    List<CrmChatStage> _theChatStages = _commonRepository.getChatStages(_theProjectType, _c.getGroupid(), _stateid, _theTitleid);
                                    if (_theChatStages != null && _theChatStages.size() > 0) {
                                        Optional<CrmChatStage> _chatStage = _theChatStages.stream().filter(x -> x.getStageid() == _c.getChatstageid()).findFirst();
                                        if (_chatStage.isPresent()) {
                                            _item.setCurrentchatstagename(_chatStage.get().getStagename());
                                        }
                                    }
                                }
                            }

                            lawyerchatgroups.add(_item);
                        }
                    }
                }
                _responseStage.setLawyerchatgroups(lawyerchatgroups);
                _stageResponse.add(_responseStage);
            }
            _detailResponse.setStagedatas(_stageResponse);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _detailResponse;
    }

    //列表
    public List<ProjectList> getProjectList(ProjectGetListRequest _request, int userid, String forType) {

        SimpleDateFormat _dataFormat24Hour = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        List<ProjectList> _projects = new ArrayList<>();
        try {

            String _searchKey = "";
            if (_request != null) {
                _searchKey = _request.getSearchkey();
            }

            List<CrmProject> _list = getProjectList(_request, userid);
            if (forType == "task") {
                _list = getProjectListForTask(_searchKey, userid);
            }

            for (CrmProject _p : _list) {
                String _projectId = _p.getRecid();
                List<CrmProjectStage2> _stageList = getProjectStageList2(_projectId, forType);

                //委托人和对方当事人
                List<CrmProjectClient> _clientList = getProjectClient(_projectId);
                List<CrmProjectClient> _clients = _clientList.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.Client.getPersonType()).collect(Collectors.toList());

                //团队成员
                List<CrmProjectMember> _memberList = getProjectMember(_projectId, userid);

                List<ProjectListStage> _responseStages = new ArrayList<>();
                for (CrmProjectStage2 _stage : _stageList) {

                    if (forType == "task") {
                        if (_stage.getStagestatus() == 2) {
                            continue;
                        }
                    }

                    ProjectListStage _listStage = new ProjectListStage();
                    _listStage.setStagename(_stage.getStagename());
                    _listStage.setStageid(_stage.getStageid());

                    if (_stage.getStagestatus() == 2) {
                        _listStage.setIscomplete(true);
                    } else {
                        _listStage.setIscomplete(false);
                    }
                    List<String> _clientNames = new ArrayList<>();
                    List<CrmProjectClient> _tmpClients = _clients.stream().filter(x -> x.getStageid() == _stage.getStageid()).collect(Collectors.toList());
                    for (CrmProjectClient c : _tmpClients) {
                        _clientNames.add(c.getName());
                    }
                    _listStage.setClients(_clientNames);

                    //判断是否是主办人
                    boolean _isHost = false;
                    boolean _inLawyermember = false;
                    List<CrmProjectMember> _tmpMembers = _memberList.stream().filter(x -> x.getStageid() == _stage.getStageid()).collect(Collectors.toList());
                    if (_tmpMembers != null && _tmpMembers.size() > 0) {
                        List<CrmProjectMember> _tmpMembers2 = _tmpMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()
                                && x.getUserid() == userid && x.ishost()).collect(Collectors.toList());
                        if (_tmpMembers2 != null && _tmpMembers2.size() > 0) {
                            _isHost = true;
                        }

                        List<CrmProjectMember> _tmpLawyerMembers = _tmpMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()
                                && x.getUserid() == userid).collect(Collectors.toList());
                        if (_tmpLawyerMembers != null && _tmpLawyerMembers.size() > 0) {
                            _inLawyermember = true;
                        }
                    }
                    _listStage.setIshost(_isHost);
                    _listStage.setInlawyermember(_inLawyermember);

                    //登陆用户参与的阶段才显示
                    if (forType == "task") {
                        long _theMemberCount = _memberList.stream().filter(x -> x.getStageid() == _stage.getStageid() && x.getUserid() == userid).count();
                        if (_theMemberCount > 0) {
                            _responseStages.add(_listStage);
                        }
                    } else {
                        _responseStages.add(_listStage);
                    }

                }
                ProjectList _tmpProjectList = toProjectList(_p);
                _tmpProjectList.setCompletedtime(_dataFormat24Hour.format(_p.getCompletedtime()));
                _tmpProjectList.setStages(_responseStages);
                _tmpProjectList.setProjecttype(_p.getProjecttype());
                if (_p.getProjectstatus() == BaseEnum.ProjectStatusType.Complete.getProjectStatusType()) {
                    _tmpProjectList.setIscomplete(true);
                } else {
                    _tmpProjectList.setIscomplete(false);
                }

                if (forType == "task") {
                    if (_tmpProjectList.getStages() != null && _tmpProjectList.getStages().size() > 0) {
                        _projects.add(_tmpProjectList);
                    }
                } else {
                    _projects.add(_tmpProjectList);
                }


            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }

        return _projects;
    }

    public List<CrmProjectStage> getProjectStages(ProjectStageGetRequest _request) {

        String _strSql = " select recid,recname,recorder,datastageid,stagetype,false as iscomplete " +
                " from crm_project_stage " +
                " where recstatus=1 " +
                " and  stagetype=0 " +
                " and  projecttype=:projecttype" +
                " order by recorder asc ";

        List<CrmProjectStage> _list = new ArrayList<>();
        try {

            Map<String, Object> _params = new HashMap<>();
            _params.put("projecttype", _request.getProjecttype());
            _list = getEntitys(_strSql, _params, CrmProjectStage.class);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _list;
    }

    //法庭
    public List<CrmProjectCourt> getProjectCourts(ProjectCourtGetRequest _request) {

        int _pageindex = _request.getPageindex();
        int _pageSize = _request.getPagesize();
        int _offset = (_pageindex - 1) * _pageSize;
        List<CrmProjectCourt> _list = new ArrayList<>();
        try {

            String _searchKey = _request.getName().trim();
            String _strCountSql = " select count(1) from crm_project_court where recstatus=1  ";
            String strSql = " select recid,recname " +
                    " from crm_project_court " +
                    " where recstatus=1 ";

            String _whereSql = " and recname like" + "'%" + _searchKey + "%'";
            if (_request != null) {

                if (!_searchKey.isEmpty()) {
                    _strCountSql += _whereSql;
                    strSql += _whereSql;
                } else {
                    strSql += " order by recid asc limit " + _pageSize + " offset " + _offset;
                }
            }
            _list = getEntitys(strSql, null, CrmProjectCourt.class);
            int _count = getEntityCount(_strCountSql, null);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _list;
    }

    //案由
    public List<ProjectCause> getProjectCause(ProjectCaseGetRequest _request) {
        int _parentid = _request.getParentid();
        String _searchKey = _request.getName();
        int _projecttype = _request.getProjecttype();

        List<ProjectCause> _resultCause = new ArrayList<>();
        List<CrmProjectCause> _list = new ArrayList<>();

        try {
            String _where_name_sql = "";
            if (!_request.getName().isEmpty()) {
                _where_name_sql = " and p.recname like" + "'%" + _searchKey + "%'";
            }
            String _where_parentid_sql = "";
            if (_parentid > -1) {
                _where_parentid_sql = " and p.parentid=" + _parentid;
            }

            String strSql = " select p.recid,p.recname,p.parentid,  " +
                    " (select count(1) from crm_project_cause where parentid=p.recid ) as childcount" +
                    " from crm_project_cause p " +
                    " where p.recstatus=1 and projecttype= " + _projecttype;

            strSql = strSql + _where_parentid_sql + _where_name_sql;
            _list = getEntitys(strSql, null, CrmProjectCause.class);
            for (CrmProjectCause _c : _list) {
                _resultCause.add(toProjectCause(_c));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _resultCause;
    }

    //项目文件夹
    public List<CrmProjectFolder> getProjectFolder(ProjectFolderGetRequest _request) {

        String _strSql = " select recid,recname,stageid,foldertype,relatedid,reccreator,prefixname,innerfoldertype,islawyerfolder  " +
                " from crm_project_folder " +
                " where recstatus=1 " +
                " and projectid=:projectid " +
                " and stageid=:stageid ";

        int _projectType = _request.getProjecttype();
        int _stageid = _request.getStageid();

        List<CrmProjectFolder> _list = new ArrayList<>();
        try {
            Map<String, Object> _params = new HashMap<>();
            _params.put("projectid", _request.getProjectid());
            _params.put("stageid", _request.getStageid());
            _list = getEntitys(_strSql, _params, CrmProjectFolder.class);

            //虚拟文件夹
            List<ProjectFolderResponse> _responses = new ArrayList<>();
            List<CrmProjectBasicFolder> _baseFolders = getProjectBasicFolder(_projectType);

            //项目文件夹
            int _commonStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
            List<CrmProjectBasicFolder> _commonStageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _commonStageFolderType).collect(Collectors.toList());
            for (CrmProjectBasicFolder _f : _commonStageFolders) {
                ProjectFolderResponse _r = new ProjectFolderResponse();
                _r.setClientid("");
                _r.setFolderid(UUID.randomUUID().toString());
                _r.setFoldername(_f.getRecname());
                _r.setFoldertype(_f.getRectype());
                _responses.add(_r);
            }

            //阶段文件夹
            List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);
            List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            String _stageName = _currentSageNameList.get(0).getStagename();
            String _fomratStageName = "(" + _stageName + ")";

            //stages
            int _stageFolderType = BaseEnum.ProjectFolderType.Stage.getProjectFolderType();
            List<CrmProjectBasicFolder> _stageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _stageFolderType).collect(Collectors.toList());
            for (CrmProjectBasicFolder _f : _stageFolders) {
                ProjectFolderResponse _r = new ProjectFolderResponse();
                _r.setClientid("");
                _r.setFolderid(UUID.randomUUID().toString());
                _r.setFoldername(_fomratStageName + _f.getRecname());
                _r.setFoldertype(_f.getRectype());
                _responses.add(_r);
            }


            //委托人
            int _clientStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
            List<CrmProjectBasicFolder> _clientStageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _clientStageFolderType).collect(Collectors.toList());

            List<ProjectClient> _clients = _request.getClients();
            for (ProjectClient _c : _clients) {
                for (CrmProjectBasicFolder _f : _clientStageFolders) {

                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setClientid(_c.getClientid());
                    _r.setFolderid(UUID.randomUUID().toString());
                    _r.setFoldername(_fomratStageName + _f.getRecname());
                    _r.setFoldertype(_f.getRectype());
                    _responses.add(_r);
                }
            }

            //对方当事人
            int _ligigantStageFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();
            List<CrmProjectBasicFolder> _ligigantStageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _ligigantStageFolderType).collect(Collectors.toList());
            List<ProjectClient> _litigants = _request.getLitigants();
            for (ProjectClient _c : _clients) {
                for (CrmProjectBasicFolder _f : _ligigantStageFolders) {

                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setClientid(_c.getClientid());
                    _r.setFolderid(UUID.randomUUID().toString());
                    _r.setFoldername(_fomratStageName + _f.getRecname());
                    _r.setFoldertype(_f.getRectype());
                    _responses.add(_r);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _list;
    }

    //获取虚拟文件夹
    public List<ProjectFolderResponse> getTempFolder(ProjectFolderGetRequest _request, int userid) {
        List<ProjectFolderResponse> _responses = new ArrayList<>();
        List<CrmProjectFolder> _list = new ArrayList<>();
        try {

            String _projectid = _request.getProjectid();
            int _projectType = _request.getProjecttype();
            int _stageid = _request.getStageid();

            int _commonStageFolderType = BaseEnum.ProjectFolderType.Common.getProjectFolderType();
            int _stageFolderType = BaseEnum.ProjectFolderType.Stage.getProjectFolderType();
            int _clientStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
            int _ligigantStageFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();

            //get all folder
            List<CrmProjectFolder> _folders = getProjectFoldersById(_projectid);

            //basic folder
            List<CrmProjectBasicFolder> _baseFolders = getProjectBasicFolder(_projectType);

            //project stage members
            boolean _isLawyerMember = false;
            if (!_projectid.isEmpty()) {
                List<CrmProjectMember> _members = getProjectMember(_projectid, userid);
                List<CrmProjectMember> _tmpMembers = _members.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType() && x.getUserid() == userid).collect(Collectors.toList());
                if (_tmpMembers != null && _tmpMembers.size() > 0) {
                    _isLawyerMember = true;
                }
            } else {
                _isLawyerMember = true;
            }

            //get special folder
            String _realFolderName = "";
            List<CrmPorjectFolderSpecial> _folderSpecials = getProjectFolderSpecial(_projectType, _stageid);
            if (_folderSpecials != null && _folderSpecials.size() > 0) {
                CrmPorjectFolderSpecial _special = _folderSpecials.get(0);
                _realFolderName = _special.getShowname();
            }

            //stage fodler name
            List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);
            List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            String _stageName = _currentSageNameList.get(0).getStagename();
            String _fomratStageName = "(" + _stageName + ")";

            //get old project folder
            List<CrmProjectFolder> _oldCommonFolders = _folders.stream().filter(x -> x.getStageid() == 0 && x.getFoldertype() == _commonStageFolderType).collect(Collectors.toList());
            if (_oldCommonFolders == null || _oldCommonFolders.size() == 0) {
                List<CrmProjectBasicFolder> _commonStageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _commonStageFolderType).collect(Collectors.toList());
                for (CrmProjectBasicFolder _f : _commonStageFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();

                    _r.setClientid("");
                    _r.setFolderid(UUID.randomUUID().toString());
                    _r.setFoldername(_f.getRecname());
                    _r.setPartanme(_f.getRecname());
                    _r.setFoldertype(_f.getRectype());
                    _r.setInnerfoldertype(_f.getInnerfoldertype());
                    _r.setLawyerfolder(false);

                    _responses.add(_r);

                }
            } else {
                for (CrmProjectFolder _f : _oldCommonFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setClientid(_f.getRelatedid());
                    _r.setFolderid(_f.getRecid());
                    _r.setFoldername(_f.getRecname());
                    _r.setPartanme(_f.getRecname());
                    _r.setFoldertype(_f.getFoldertype());
                    _r.setInnerfoldertype(_f.getInnerfoldertype());
                    _r.setLawyerfolder(false);
                    _responses.add(_r);

                }
            }

            //get old state folder
            String _lawyerFolderPrefix = "律师协作团队";
            List<CrmProjectFolder> _oldStageFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _stageFolderType).collect(Collectors.toList());
            if (_oldStageFolders == null || _oldStageFolders.size() == 0) {
                List<CrmProjectBasicFolder> _stageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _stageFolderType).collect(Collectors.toList());
                for (CrmProjectBasicFolder _f : _stageFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();

                    String _finalFolderName = _fomratStageName + _f.getRecname();
                    if (_f.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolder.getDefaultFolderType() && !_isLawyerMember) {
                        continue;
                    }

                    //只有律师协作团队可以看到的文件夹
                    if (_f.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolder.getDefaultFolderType()) {
                        _finalFolderName = _lawyerFolderPrefix + _finalFolderName;
                        _r.setLawyerfolder(true);
                    }

                    _r.setFoldername(_finalFolderName);
                    _r.setPartanme(_finalFolderName);
                    _r.setClientid("");
                    _r.setFolderid(UUID.randomUUID().toString());
                    _r.setFoldertype(_f.getRectype());
                    _r.setInnerfoldertype(_f.getInnerfoldertype());

                    _responses.add(_r);

                }
            } else {
                for (CrmProjectFolder _f : _oldStageFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setClientid(_f.getRelatedid());
                    _r.setFolderid(_f.getRecid());
                    _r.setFoldername(_f.getPrefixname() + _f.getRecname());
                    _r.setPartanme(_f.getRecname());
                    _r.setFoldertype(_f.getFoldertype());
                    _r.setInnerfoldertype(_f.getInnerfoldertype());
                    _r.setLawyerfolder(_f.islawyerfolder());

                    //过滤律师协作团队文件夹
                    if (_f.islawyerfolder() && !_isLawyerMember) {
                        continue;
                    }
                    _responses.add(_r);
                }
            }

            //clients
            List<CrmProjectFolder> _oldClientFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _clientStageFolderType).collect(Collectors.toList());
            List<ProjectClient> _clients = _request.getClients();
            List<CrmProjectBasicFolder> _baseClientStageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _clientStageFolderType).collect(Collectors.toList());
            if (_oldClientFolders == null || _oldClientFolders.size() == 0) {
                for (ProjectClient _c : _clients) {
                    for (CrmProjectBasicFolder _f : _baseClientStageFolders) {
                        ProjectFolderResponse _r = new ProjectFolderResponse();

                        if (_f.getIsReplaceable() && !_realFolderName.isEmpty()) {
                            _f.setRecname("正式提交给" + _realFolderName + "的材料");
                        }

                        _r.setClientid(_c.getClientid());
                        _r.setFolderid(UUID.randomUUID().toString());
                        _r.setFoldername(_c.getName() + _fomratStageName + _f.getRecname());
                        _r.setPartanme(_fomratStageName + _f.getRecname());
                        _r.setFoldertype(_f.getRectype());
                        _r.setInnerfoldertype(_f.getInnerfoldertype());
                        _r.setLawyerfolder(false);

                        _responses.add(_r);

                    }
                }
            } else {
                //old client folders
                for (CrmProjectFolder _f : _oldClientFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setClientid(_f.getRelatedid());
                    _r.setFolderid(_f.getRecid());
                    _r.setFoldername(_f.getPrefixname() + _f.getRecname());
                    _r.setPartanme(_f.getRecname());
                    _r.setFoldertype(_f.getFoldertype());
                    _r.setInnerfoldertype(_f.getInnerfoldertype());
                    _r.setLawyerfolder(_f.islawyerfolder());
                    _responses.add(_r);

                }

                //new client folders
                List<ProjectClient> _newClients = _clients.stream().filter(x -> x.getIsnew()).collect(Collectors.toList());
                if (_newClients != null && _newClients.size() > 0) {
                    for (ProjectClient _c : _newClients) {
                        for (CrmProjectBasicFolder _f : _baseClientStageFolders) {
                            ProjectFolderResponse _r = new ProjectFolderResponse();

                            if (_f.getIsReplaceable() && !_realFolderName.isEmpty()) {
                                _f.setRecname("正式提交给" + _realFolderName + "的材料");
                            }

                            //正式提交给法院的材料
                            _r.setClientid(_c.getClientid());
                            _r.setFolderid(UUID.randomUUID().toString());
                            _r.setFoldername(_c.getName() + _fomratStageName + _f.getRecname());
                            _r.setPartanme(_fomratStageName + _f.getRecname());
                            _r.setFoldertype(_f.getRectype());
                            _r.setInnerfoldertype(_f.getInnerfoldertype());
                            _r.setLawyerfolder(false);
                            _responses.add(_r);
                        }
                    }
                }
            }

            //ligigants
            List<CrmProjectFolder> _oldLigigantFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _ligigantStageFolderType).collect(Collectors.toList());
            List<ProjectClient> _litigants = _request.getLitigants();
            List<CrmProjectBasicFolder> _baseLigigantStageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _ligigantStageFolderType).collect(Collectors.toList());
            if (_oldLigigantFolders == null || _oldLigigantFolders.size() == 0) {

                for (ProjectClient _c : _litigants) {
                    for (CrmProjectBasicFolder _f : _baseLigigantStageFolders) {
                        ProjectFolderResponse _r = new ProjectFolderResponse();
                        if (_f.getIsReplaceable() && !_realFolderName.isEmpty()) {
                            _f.setRecname("提交给" + _realFolderName + "的材料");
                        }
                        _r.setClientid(_c.getClientid());
                        _r.setFolderid(UUID.randomUUID().toString());
                        _r.setFoldername(_c.getName() + _fomratStageName + _f.getRecname());
                        _r.setPartanme(_fomratStageName + _f.getRecname());
                        _r.setFoldertype(_f.getRectype());
                        _r.setInnerfoldertype(_f.getInnerfoldertype());
                        _r.setLawyerfolder(false);
                        _responses.add(_r);

                    }
                }
            } else {
                //old ligigants folder
                for (CrmProjectFolder _f : _oldLigigantFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setClientid(_f.getRelatedid());
                    _r.setFolderid(_f.getRecid());
                    _r.setFoldername(_f.getPrefixname() + _f.getRecname());
                    _r.setPartanme(_f.getRecname());
                    _r.setFoldertype(_f.getFoldertype());
                    _r.setInnerfoldertype(_f.getInnerfoldertype());
                    _r.setLawyerfolder(_f.islawyerfolder());
                    _responses.add(_r);

                }

                //new ligigant folders
                List<ProjectClient> _newLitigants = _litigants.stream().filter(x -> x.getIsnew()).collect(Collectors.toList());
                if (_newLitigants != null && _newLitigants.size() > 0) {
                    for (ProjectClient _c : _newLitigants) {
                        for (CrmProjectBasicFolder _f : _baseLigigantStageFolders) {
                            ProjectFolderResponse _r = new ProjectFolderResponse();
                            if (_f.getIsReplaceable() && !_realFolderName.isEmpty()) {
                                _f.setRecname("提交给" + _realFolderName + "的材料");
                            }
                            _r.setClientid(_c.getClientid());
                            _r.setFolderid(UUID.randomUUID().toString());
                            _r.setFoldername(_c.getName() + _fomratStageName + _f.getRecname());
                            _r.setPartanme(_fomratStageName + _f.getRecname());
                            _r.setFoldertype(_f.getRectype());
                            _r.setInnerfoldertype(_f.getInnerfoldertype());
                            _r.setLawyerfolder(false);
                            _responses.add(_r);

                        }
                    }
                }
            }

            //自定义文件夹
            List<CrmProjectFolder> _userDefinefolders = _folders.stream().filter(x -> x.getStageid() == _stageid
                    && x.getFoldertype() == BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType()).collect(Collectors.toList());
            for (CrmProjectFolder _f : _userDefinefolders) {
                ProjectFolderResponse _r = new ProjectFolderResponse();

                if (!_isLawyerMember && _f.islawyerfolder()) {
                    continue;
                }
                _r.setClientid(_f.getRelatedid());
                _r.setFolderid(_f.getRecid());
                _r.setFoldername(_f.getRecname());
                _r.setPartanme(_f.getRecname());
                _r.setFoldertype(_f.getFoldertype());
                _r.setInnerfoldertype(_f.getInnerfoldertype());
                _r.setLawyerfolder(_f.islawyerfolder());
                _responses.add(_r);
            }

            for (ProjectFolderResponse _r : _responses) {
                _r.setIsselect(false);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _responses;
    }

    public List<CrmProjectDefaultFolder> getProjectDefaultFolder(ProjectFolderGetRequest _request) {

        String _strSql = " select recid,recname,recorder,replaceable,foldertype " +
                " from crm_project_default_folder " +
                " where recstatus=1 " +
                " and projecttype=:projecttype " +
                "  order by recorder asc ";

        List<CrmProjectDefaultFolder> _list = new ArrayList<>();
        try {
            Map<String, Object> _params = new HashMap<>();
            _params.put("projecttype", _request.getProjecttype());
            _list = getEntitys(_strSql, _params, CrmProjectDefaultFolder.class);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _list;
    }

    //获取项目聊天基础数据
    public ProjectChatResponse getProjectChatInfo() {
        ProjectChatResponse _response = new ProjectChatResponse();
        List<ProjectChatStage> _stages = new ArrayList<>();
        List<ProjectChatTopic> _topics = new ArrayList<>();

        try {
            String _stageSql = " select recid,recname from crm_project_group_stage ";
            List<CrmProjectChatStage> _stageList = getEntitys(_stageSql, null, CrmProjectChatStage.class);
            for (CrmProjectChatStage _stage : _stageList) {
                ProjectChatStage stage = toProjectChatStage(_stage);
                _stages.add(stage);
            }

            String _topicSql = " select recid,recname,group_stageid from crm_project_chat_topic ";
            List<CrmProjectChatTopic> _topicList = getEntitys(_stageSql, null, CrmProjectChatTopic.class);
            for (CrmProjectChatTopic _topic : _topicList) {
                ProjectChatTopic topic = toProjectChatTopic(_topic);
                _topics.add(topic);
            }
            _response.setStages(_stages);
            _response.setTopics(_topics);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _response;
    }

    //添加团队成员
    @Transactional
    public int addMember(ProjectMemberAddRequest _request, String groupid, int userid) {

        int _result = 0;
        int _finalResult = 0;
        try {
            String _projectid = _request.getProjectid();
            String _strSql = " insert into crm_project_member(recid,projectid,stageid,groupid,userid,ismanager,reccreator,grouptype,innergrouptype) " +
                    " values(:recid,:projectid,:stageid,:groupid,:userid,:ismanager,:reccreator,:grouptype,:innergrouptype)";
            for (ProjectMember _member : _request.getMembers()) {
                Map<String, Object> _params = new HashMap<>();
                _params.put("recid", UUID.randomUUID().toString());
                _params.put("projectid", _request.getProjectid());
                _params.put("stageid", _request.getStageid());
                _params.put("groupid", groupid);
                _params.put("userid", _member.getUserid());
                _params.put("ismanager", _member.getIsmanager());
                _params.put("reccreator", userid);
                _params.put("grouptype", _member.getGrouptype());
                _params.put("innergrouptype", _member.getInnergrouptype());


                _result = updateEntity(_strSql, _params);
                _finalResult += _result;
            }
        } catch (Exception ex) {
            throw ex;
        }
        return _finalResult;
    }

    //删除团队成员
    @Transactional
    public int deleteMember(ProjectMemberDeleteRequest _request, String groupid, int userid) {
        int _result = 0;
        int _finalResult = 0;
        try {

            String _tmpSql = " select recid,stageid,groupid,userid, '' as username,ismanager,ishost,grouptype,innergrouptype,relatedid " +
                    " from crm_project_member " +
                    " where recstatus=1 " +
                    " and  projectid=:projectid" +
                    " and stageid=:stageid" +
                    " and groupid=:groupid" +
                    " and  userid in (%s)";

            String _useridSql = "";
            List<String> ids = new ArrayList<>();
            for (ProjectMember _member : _request.getMembers()) {
                ids.add(Integer.toString(_member.getUserid()));
            }
            _useridSql = String.join(",", ids);
            String _selectSql = String.format(_tmpSql, _useridSql);

            Map<String, Object> _params = new HashMap<>();
            _params.put("projectid", _request.getProjectid());
            _params.put("stageid", _request.getStageid());
            _params.put("groupid", groupid);
            List<CrmProjectMember> _members = getEntitys(_selectSql, _params, CrmProjectMember.class);


            String _deleteSql = "update crm_project_member set recstatus=0 where recid=:recid";
            for (CrmProjectMember _member : _members) {
                _params.clear();
                _params.put("recid", _member.getRecid());
                _result = updateEntity(_deleteSql, _params);
                _finalResult += _result;
            }
        } catch (Exception ex) {
            throw ex;
        }
        return _finalResult;
    }

    //获取聊天组的成员
    public List<ProjectMember> getProjectMember(ProjectMemberGetRequest _request) {

        String strMemberSql = " select recid,stageid,groupid,userid,u.username,ismanager,grouptype,innergrouptype,projectid " +
                " from crm_project_member m " +
                " inner join crm_user u on m.userid=u.id " +
                " where m.recstatus=1 " +
                " and  groupid=:groupid ";

        List<ProjectMember> _members = new ArrayList<>();
        try {

            Map<String, Object> _params = new HashMap<>();
            _params.put("groupid", _request.getGroupid());
            List<CrmProjectMember> _memberList = getEntitys(strMemberSql, _params, CrmProjectMember.class);
            for (CrmProjectMember _member : _memberList) {
                ProjectMember member = toProjectMember(_member);
                _members.add(member);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _members;
    }

    private int getMinChatStageid() {

        int _stageid = 0;
        List<ChatStage> _stages = new ArrayList<>();
        String _stageSql = " select recid,recname,stagetype,0 as branchstatus from crm_chat_stage where recstatus=1 order by recorder asc";
        List<CrmChatStage> _stageList = getEntitys(_stageSql, null, CrmChatStage.class);

        if (_stageList.size() > 0) {
            CrmChatStage _chatStage = _stageList.get(0);
            _stageid = _chatStage.getStageid();
        }
        return _stageid;
    }

    //项目文件夹
    public List<CrmProjectType> getProjectTypes() {

        String _strSql = "select recid,recname,recstatus,recorder " +
                " from crm_project_type " +
                " where recstatus=1 " +
                " order by recorder asc";
        List<CrmProjectType> _list = new ArrayList<>();
        try {
            _list = getEntitys(_strSql, null, CrmProjectType.class);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _list;
    }

    //设置项目阶段状态
    @Transactional
    public int updateProjectStageStatusSimple(String projectid, int stageid, int stageStatus, int userid) throws Exception {
        int _result = 0;
        try {

            List<CrmProjectStageRelate> _stageRelates = getProjectStageRelate(projectid);
            List<CrmProjectStageRelate> _currretnStageRelate = _stageRelates.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
            CrmProjectStageRelate _stageRelate = _currretnStageRelate.get(0);
            String _recid = _stageRelate.getRecid();

            String _strSql = " update crm_project_stage_relate set stagestatus=:stagestatus, completedtime=now() where recid=:recid";
            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", _recid);
            _params.put("stagestatus", stageStatus);
            _result = updateEntity(_strSql, _params);
            if (_result > 0) {

                boolean _isActive = false;
                if (stageStatus == BaseEnum.StageStatus.Complete.getStageStatus()) {
                } else {
                    _isActive = true;
                }

                List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(projectid);
                List<CrmChatGroupPart> _stageChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
                for (CrmChatGroupPart c : _stageChatGroups) {
                    _commonRepository.setTaskChatGroupActive(c.getGroupid(), _isActive);
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    public List<CrmCommonItem> getProjectTitle(int projectType, int stageid) {

        List<CrmCommonItem> _result = new ArrayList<>();
        int _stageid = stageid;
        try {

            ProjectStageGetRequest _getRequest = new ProjectStageGetRequest();
            _getRequest.setProjecttype(projectType);

            List<CrmProjectStage> _projectStages = getProjectStages(_getRequest);
            List<CrmProjectStage> _currentStage = _projectStages.stream().filter(x -> x.getStageid() == stageid && x.getDatastageid() > 0).collect(Collectors.toList());
            if (_currentStage != null && _currentStage.size() > 0) {
                _stageid = _currentStage.get(0).getDatastageid();
            }

            String _strSql = " select recid,recname " +
                    "from crm_project_title" +
                    " where recstatus=1" +
                    " and  projecttype=:projecttype" +
                    " and stageid=:stageid ";

            Map<String, Object> _params = new HashMap<>();
            _params.put("projecttype", projectType);
            _params.put("stageid", _stageid);
            _result = getEntitys(_strSql, _params, CrmCommonItem.class);

            return _result;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }

    // 添加用户自定义身份
    @Transactional
    public int saveProjectTitle(ProjectSaveTitleRequest _request, int userid) {

        int _result = 0;
        String _strSql = " insert into crm_project_title(recid,projecttype,stageid,titletype,recname)" +
                " values(:recid,:projecttype,:stageid,:titletype,:recname)";
        try {
            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", UUID.randomUUID().toString());
            _params.put("projecttype", _request.getProjecttype());
            _params.put("stageid", _request.getStageid());
            _params.put("titletype", BaseEnum.ProjectTitleType.UserDefine.getProjectTitleType());
            _params.put("recname", _request.getTitle());
            _result = updateEntity(_strSql, _params);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }


    public List<CrmProjectInfoField> getProjectInfoFields(ProjectInfoFieldGetRequest _request, int userid) {
        List<CrmProjectInfoField> _list = new ArrayList<>();
        try {

            int _stageid = _request.getStageid();
            EntityManager _entityManager = getEntityManager();

            String _strSql = " select recid,recname,recorder,datastageid,stagetype " +
                    " from crm_project_stage where recid=:recid ";
            javax.persistence.Query _query = _entityManager.createNativeQuery(_strSql, CrmProjectStageAll.class);
            _query.setParameter("recid", _stageid);
            List<CrmProjectStageAll> _stages = _query.getResultList();
            if (_stages != null && _stages.size() > 0) {
                CrmProjectStageAll _stage = _stages.get(0);
                if (_stage.getStagetype() == BaseEnum.StageType.Define.getStageType()) {
                    //24 为自定义阶段，所有自定义阶段使用相同的字段
                    _stageid = 24;
                }

            }

            _strSql = " select recid, fieldname,displayname,url " +
                    " from   crm_project_info_field " +
                    " where recstatus=1 " +
                    "  and  projecttype=:projecttype " +
                    "  and stageid=:stageid " +
                    " order by recorder asc ";
            _query = _entityManager.createNativeQuery(_strSql, CrmProjectInfoField.class);
            _query.setParameter("projecttype", _request.getProjecttype());
            _query.setParameter("stageid", _stageid);
            _list = _query.getResultList();


        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _list;
    }


    //为什么要这么处理呢？
    public List<ProjectFolderResponse> getProjectTaskFolder(ProjectTaskFolderGetRequest _request, int userid) {
        List<ProjectFolderResponse> _responses = new ArrayList<>();
        List<CrmProjectFolder> _list = new ArrayList<>();
        try {

            String _projectid = _request.getProjectid();
            int _projectType = _request.getProjecttype();
            int _stageid = _request.getStageid();

            int _commonStageFolderType = BaseEnum.ProjectFolderType.Common.getProjectFolderType();
            int _stageFolderType = BaseEnum.ProjectFolderType.Stage.getProjectFolderType();
            int _clientStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
            int _ligigantStageFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();

            //用户自定义文件夹
            int _userDefineStageFolderType = BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType();


            //get all folder
            List<CrmProjectFolder> _folders = getProjectFoldersById(_projectid);

            //basic folder
            List<CrmProjectBasicFolder> _baseFolders = getProjectBasicFolder(_projectType);

            //stage fodler name
            List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);
            List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            String _stageName = _currentSageNameList.get(0).getStagename();
            String _fomratStageName = "(" + _stageName + ")";


            //律师协作团队可以看到的文件夹
            boolean _isInLawyerMember = false;
            List<CrmProjectMember> _members = getProjectMember(_projectid, userid);
            List<CrmProjectMember> _stageMembers = _members.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            long _theLawyerCount = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType() && x.getUserid() == userid).count();
            if (_theLawyerCount > 0) {
                _isInLawyerMember = true;
            }

            boolean _isInClientMember = false;
            if (!_isInLawyerMember) {
                long _theClientCount = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType() && x.getUserid() == userid).count();
                if (_theClientCount > 0) {
                    _isInClientMember = true;
                }
            }


            //get old project folder
            List<CrmProjectFolder> _oldCommonFolders = _folders.stream().filter(x -> x.getStageid() == 0 && x.getFoldertype() == _commonStageFolderType).collect(Collectors.toList());
            if (_oldCommonFolders == null && _oldCommonFolders.size() == 0) {
                List<CrmProjectBasicFolder> _commonStageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _commonStageFolderType).collect(Collectors.toList());
                for (CrmProjectBasicFolder _f : _commonStageFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setLawyerfolder(false);
                    _r.setClientid("");
                    _r.setFolderid(UUID.randomUUID().toString());
                    _r.setFoldername(_f.getRecname());
                    _r.setPartanme(_f.getRecname());
                    _r.setFoldertype(_f.getRectype());
                    _r.setInnerfoldertype(_f.getInnerfoldertype());
                    _responses.add(_r);

                }
            } else {
                for (CrmProjectFolder _f : _oldCommonFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setLawyerfolder(false);
                    _r.setClientid(_f.getRelatedid());
                    _r.setFolderid(_f.getRecid());
                    _r.setFoldername(_f.getRecname());
                    _r.setPartanme(_f.getRecname());
                    _r.setFoldertype(_f.getFoldertype());
                    _r.setInnerfoldertype(0);
                    _responses.add(_r);

                }
            }

            //get old state folder
            List<CrmProjectFolder> _oldStageFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _stageFolderType).collect(Collectors.toList());
            if (_oldStageFolders == null || _oldStageFolders.size() == 0) {
                List<CrmProjectBasicFolder> _stageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _stageFolderType).collect(Collectors.toList());
                List<CrmProjectBasicFolder> _finalStageFolders = _stageFolders;
                if (_isInClientMember) {
                    _finalStageFolders = _baseFolders.stream().filter(x -> x.getRectype() == _stageFolderType
                            && x.getFoldertype() == BaseEnum.DefaultFolderType.ClientFolder.getDefaultFolderType()).collect(Collectors.toList());
                }
                if (_finalStageFolders != null) {
                    for (CrmProjectBasicFolder _f : _finalStageFolders) {
                        ProjectFolderResponse _r = new ProjectFolderResponse();
                        _r.setLawyerfolder(false);
                        _r.setClientid("");
                        _r.setFolderid(UUID.randomUUID().toString());
                        _r.setFoldername(_fomratStageName + _f.getRecname());
                        if (_f.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolder.getDefaultFolderType()) {
                            _r.setFoldername("律师协作团队" + _fomratStageName + _f.getRecname());
                            _r.setLawyerfolder(true);

                        } else {
                            _r.setFoldername(_fomratStageName + _f.getRecname());
                        }

                        _r.setPartanme(_fomratStageName + _f.getRecname());
                        _r.setFoldertype(_f.getRectype());
                        _r.setInnerfoldertype(_f.getInnerfoldertype());
                        _responses.add(_r);
                    }
                }

            } else {
                List<CrmProjectFolder> _finalStageFolders = _oldStageFolders;
                if (_isInClientMember) {
                    _finalStageFolders = _oldStageFolders.stream().filter(x -> x.islawyerfolder() == false).collect(Collectors.toList());
                }
                if (_finalStageFolders != null) {
                    for (CrmProjectFolder _f : _finalStageFolders) {
                        ProjectFolderResponse _r = new ProjectFolderResponse();
                        _r.setLawyerfolder(false);
                        if (_f.islawyerfolder()) {
                            _r.setLawyerfolder(true);
                        }
                        _r.setClientid(_f.getRelatedid());
                        _r.setFolderid(_f.getRecid());
                        _r.setFoldername(_f.getPrefixname() + _f.getRecname());
                        _r.setPartanme(_f.getRecname());
                        _r.setFoldertype(_f.getFoldertype());
                        _r.setInnerfoldertype(0);
                        _responses.add(_r);
                    }
                }
            }

            //clients
            List<CrmProjectFolder> _oldClientFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _clientStageFolderType).collect(Collectors.toList());
            //old client folders
            for (CrmProjectFolder _f : _oldClientFolders) {
                ProjectFolderResponse _r = new ProjectFolderResponse();
                _r.setLawyerfolder(false);
                _r.setClientid(_f.getRelatedid());
                _r.setFolderid(_f.getRecid());
                _r.setFoldername(_f.getPrefixname() + _f.getRecname());
                _r.setPartanme(_f.getRecname());
                _r.setFoldertype(_f.getFoldertype());
                _r.setInnerfoldertype(0);
                _responses.add(_r);
            }

            //ligigants
            List<CrmProjectFolder> _oldLigigantFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _ligigantStageFolderType).collect(Collectors.toList());
            for (CrmProjectFolder _f : _oldLigigantFolders) {
                ProjectFolderResponse _r = new ProjectFolderResponse();
                _r.setLawyerfolder(false);
                _r.setClientid(_f.getRelatedid());
                _r.setFolderid(_f.getRecid());
                _r.setFoldername(_f.getPrefixname() + _f.getRecname());
                _r.setPartanme(_f.getRecname());
                _r.setFoldertype(_f.getFoldertype());
                _r.setInnerfoldertype(0);
                _responses.add(_r);
            }

            //get user define folder
            List<CrmProjectFolder> _oldUserDefineFolders = _folders.stream().filter(x -> x.getStageid() == _stageid && x.getFoldertype() == _userDefineStageFolderType).collect(Collectors.toList());
            if (_isInLawyerMember) {
                for (CrmProjectFolder _f : _oldUserDefineFolders) {
                    ProjectFolderResponse _r = new ProjectFolderResponse();
                    _r.setLawyerfolder(false);
                    if (_f.islawyerfolder()) {
                        _r.setLawyerfolder(true);
                    }

                    _r.setClientid(_f.getRelatedid());
                    _r.setFolderid(_f.getRecid());
                    _r.setFoldername(_f.getPrefixname() + _f.getRecname());
                    _r.setPartanme(_f.getRecname());
                    _r.setFoldertype(_f.getFoldertype());
                    _r.setInnerfoldertype(0);
                    _responses.add(_r);
                }
            } else {
                if (_isInClientMember) {
                    List<CrmProjectFolder> _clientUserDefineFolders = _oldUserDefineFolders.stream().filter(x -> x.islawyerfolder() == false).collect(Collectors.toList());
                    for (CrmProjectFolder _f : _clientUserDefineFolders) {
                        ProjectFolderResponse _r = new ProjectFolderResponse();
                        _r.setLawyerfolder(false);
                        _r.setClientid(_f.getRelatedid());
                        _r.setFolderid(_f.getRecid());
                        _r.setFoldername(_f.getPrefixname() + _f.getRecname());
                        _r.setPartanme(_f.getRecname());
                        _r.setFoldertype(_f.getFoldertype());
                        _r.setInnerfoldertype(0);
                        _responses.add(_r);
                    }
                }
            }

            for (ProjectFolderResponse _r : _responses) {
                _r.setIsselect(false);
            }
            //testList.sort(Comparator.comparing(ClassName::getFieldName));
            _responses.sort(Comparator.comparing(ProjectFolderResponse::isLawyerfolder).reversed());
            //_responses.stream().sorted(x->x.isLawyerfolder()).
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _responses;
    }

    //获取登陆用户参数的阶段
    public List<ProjectStageResponse> getProjectStageWithPermission(ProjectStageRequest _request, int userid) {

        List<ProjectStageResponse> _listResonse = new ArrayList<>();
        String _strSql = " select s.recid,s.recname,s.recorder,s.datastageid,false as iscomplete  " +
                " from crm_project_stage s " +
                " inner join crm_project_member m on s.recid=m.stageid " +
                " where m.recstatus=1 " +
                " and m.projectid=:projectid " +
                " and m.userid=:userid ";
        try {

            Map<String, Object> _params = new HashMap<>();
            _params.put("projectid", _request.getProjectid());
            _params.put("userid", userid);
            List<CrmProjectStage> _list = getEntitys(_strSql, _params, CrmProjectStage.class);
            for (CrmProjectStage s : _list) {
                ProjectStageResponse _r = new ProjectStageResponse();
                _r.setStageid(s.getStageid());
                _r.setStagename(s.getStagename());
                _listResonse.add(_r);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _listResonse;
    }

    public List<ProjectList> getProjectListForTask(int userid) {

        List<ProjectList> _projects = new ArrayList<>();
        try {

            List<CrmProject> _list = getProjectList(userid);

            for (CrmProject _p : _list) {
                String _projectId = _p.getRecid();
                List<CrmProjectStage> _stageList = getProjectStageList(_projectId);
                //委托人和对方当事人
                List<CrmProjectClient> _clientList = getProjectClient(_projectId);
                List<CrmProjectClient> _clients = _clientList.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.Client.getPersonType()).collect(Collectors.toList());

                //团队成员
                List<CrmProjectMember> _memberList = getProjectMember(_projectId, userid);
                List<ProjectListStage> _responseStages = new ArrayList<>();

                for (CrmProjectStage _stage : _stageList) {
                    ProjectListStage _listStage = new ProjectListStage();
                    _listStage.setStagename(_stage.getStagename());
                    _listStage.setStageid(_stage.getStageid());

                    List<String> _clientNames = new ArrayList<>();
                    List<CrmProjectClient> _tmpClients = _clients.stream().filter(x -> x.getStageid() == _stage.getStageid()).collect(Collectors.toList());
                    for (CrmProjectClient c : _tmpClients) {
                        _clientNames.add(c.getName());
                    }
                    _listStage.setClients(_clientNames);

                    //判断是否是主办人
                    boolean _isHost = false;
                    List<CrmProjectMember> _tmpMembers = _memberList.stream().filter(x -> x.getStageid() == _stage.getStageid()).collect(Collectors.toList());
                    if (_tmpMembers != null && _tmpMembers.size() > 0) {
                        List<CrmProjectMember> _tmpMembers2 = _tmpMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()
                                && x.getUserid() == userid && x.ishost()).collect(Collectors.toList());
                        if (_tmpMembers2 != null && _tmpMembers2.size() > 0) {
                            _isHost = true;
                        }
                    }
                    _listStage.setIshost(_isHost);

                    List<CrmProjectMember> _tmp = _tmpMembers.stream().filter(x -> x.getUserid() == userid).collect(Collectors.toList());
                    if (_tmp != null && _tmp.size() > 0) {
                        _responseStages.add(_listStage);
                    }
                }
                ProjectList _tmpProjectList = toProjectList(_p);
                _tmpProjectList.setStages(_responseStages);
                _tmpProjectList.setProjecttype(_p.getProjecttype());
                _projects.add(_tmpProjectList);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _projects;
    }

    /* the inner methods */

    private int updateProjectMain(String projectid, String projectName) {

        int _result = 0;
        String _strSql = " update crm_project set recname=:recname where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", projectid);
        _params.put("recname", projectName);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    private int insertProjectClient(Session session, String projectid, int stageid, int personType, List<ProjectClient> clients) {

        int _result = 0;
        int _finalResult = 0;
        for (ProjectClient client : clients) {
            String _recid = UUID.randomUUID().toString();
            insertProjectClientSingle(projectid, stageid, personType, _recid, client);
            _finalResult += _result;
        }
        return _finalResult;
    }

    private int insertProjectClientSingle(String projectid, int stageid, int personType, String recid, ProjectClient client) {

        if (client == null) {
            return 0;
        }

        int _result = 0;
        String _strSql =
                " insert into crm_project_client(recid,projectid,stageid,rectype,title,name,contact,phone,mail,persontype,titleid)" +
                        " values(:recid,:projectid,:stageid,:rectype,:title,:name,:contact,:phone,:mail,:persontype,:titleid)";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("rectype", client.getRectype());
        _params.put("title", client.getTitle());
        _params.put("name", client.getName());
        _params.put("contact", client.getContact());
        _params.put("phone", client.getPhone());
        _params.put("mail", client.getMail());
        _params.put("persontype", personType);
        _params.put("titleid", client.getTitleid());
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    private int updateProjectClient(List<ProjectClient> clients) {

        int _result = 0;
        int _finalResult = 0;
        String _strSql =
                " update crm_project_client" +
                        " set title=:title, " +
                        " name=:name, " +
                        " contact=:contact," +
                        " phone=:phone," +
                        " mail=:mail, " +
                        " titleid=:titleid, " +
                        " rectype=:rectype " +
                        " where recid=:recid ";
        for (ProjectClient client : clients) {
            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", client.getRecid());
            _params.put("title", client.getTitle());
            _params.put("name", client.getName());
            _params.put("contact", client.getContact());
            _params.put("phone", client.getPhone());
            _params.put("mail", client.getMail());
            _params.put("titleid", client.getTitleid());
            _params.put("rectype", client.getRectype());
            _result = updateEntity(_strSql, _params);
            _finalResult += _result;
        }
        return _finalResult;
    }


    private int updateProjectClientSingle(ProjectClient client) {

        int _result = 0;

        String _strSql =
                " update crm_project_client" +
                        " set title=:title, " +
                        " name=:name, " +
                        " contact=:contact," +
                        " phone=:phone," +
                        " mail=:mail, " +
                        " titleid=:titleid, " +
                        " rectype=:rectype " +
                        " where recid=:recid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", client.getRecid());
        _params.put("title", client.getTitle());
        _params.put("name", client.getName());
        _params.put("contact", client.getContact());
        _params.put("phone", client.getPhone());
        _params.put("mail", client.getMail());
        _params.put("titleid", client.getTitleid());
        _params.put("rectype", client.getRectype());

        _result = updateEntity(_strSql, _params);


        return _result;
    }

    //获取委托人和对方当事人
    public List<CrmProjectClient> getProjectClient(String projectid) {

        String _strSql = " select recid,stageid,rectype,title,name,contact,phone,mail,persontype,titleid,projectid " +
                " from crm_project_client " +
                " where recstatus=1 " +
                " and  projectid=:projectid " +
                " order by createtime asc ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectClient> _clientList = getEntitys(_strSql, _params, CrmProjectClient.class);
        return _clientList;
    }

    private int deleteProjectClient(String recid) {

        String _strSql = " update crm_project_client set recstatus=0 where recid=:recid";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        return updateEntity(_strSql, _params);
    }

    //删除委托人和对方当事人
    private int deleteProjectClientBatch(List<CrmProjectClient> _oldProjectClient) {

        int _result = 0;
        int _finalResult = 0;

        String _strSql = " update crm_project_client set recstatus=0 where recid=:recid";
        for (CrmProjectClient client : _oldProjectClient) {
            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", client.getRecid());
            _result = updateEntity(_strSql, _params);
            _finalResult += _result;
        }
        return _finalResult;
    }

    //获取项目基本拘束
    public List<CrmProjectInfo> getProjectInfo(String projectid) {

        String _strSql = " select recid,stageid,cause_of_action,court,case_number,claim,remark,crimename,civilrequest,detentiondate,arrestdate,custodyplace " +
                " from crm_project_info " +
                " where projectid=:projectid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectInfo> _infoList = getEntitys(_strSql, _params, CrmProjectInfo.class);
        return _infoList;
    }

    //添加项目基本数据
    private int insertProjectInfo(String projectid, int stageid, ProjectStage _stage) throws Exception {
        int _result = 0;


        String _strSql =
                " insert into crm_project_info(recid,projectid,stageid,cause_of_action,court,case_number,claim,remark,crimename,civilrequest,detentiondate,arrestdate,custodyplace)" +
                        " values(:recid,:projectid,:stageid,:cause_of_action,:court,:case_number,:claim,:remark,:crimename,:civilrequest,:detentiondate,:arrestdate,:custodyplace)";


        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", UUID.randomUUID().toString());
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("cause_of_action", _stage.getInfo().getCauseofaction());
        _params.put("court", _stage.getInfo().getCourt());
        _params.put("case_number", _stage.getInfo().getCasenumber());
        _params.put("claim", _stage.getInfo().getClaim());
        _params.put("remark", "");
        //_params.put("crimename", _stage.getInfo().getCrimename());
        _params.put("crimename", "");
        _params.put("civilrequest", _stage.getInfo().getCivilrequest());

        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String _strDetentiondate = _stage.getInfo().getDetentiondate();
        if (_strDetentiondate != null && !_strDetentiondate.isEmpty()) {
            Date _detentiondate = _dataFormat.parse(_stage.getInfo().getDetentiondate());
            _params.put("detentiondate", _detentiondate);
        } else {
            _params.put("detentiondate", null);
        }
        String _strArrestdate = _stage.getInfo().getArrestdate();
        if (_strArrestdate != null && !_strArrestdate.isEmpty()) {
            Date _arrestdate = _dataFormat.parse(_strArrestdate);
            _params.put("arrestdate", _arrestdate);
        } else {
            _params.put("arrestdate", null);
        }

        _params.put("custodyplace", _stage.getInfo().getCustodyplace());
        _result = updateEntity(_strSql, _params);


        return _result;
    }

    //更新项目基本数据
    private int updateProjectInfo(ProjectStage _stage, String infoid) throws Exception {
        int _result = 0;

        String _strSql =
                " update crm_project_info " +
                        " set cause_of_action=:cause_of_action," +
                        " court=:court," +
                        " case_number=:case_number," +
                        " claim=:claim," +
                        " remark=:remark, " +
                        " crimename=:crimename," +
                        " civilrequest=:civilrequest, " +
                        " detentiondate=:detentiondate, " +
                        " arrestdate=:arrestdate, " +
                        " custodyplace=:custodyplace " +
                        " where recid=:recid ";


        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", infoid);
        _params.put("cause_of_action", _stage.getInfo().getCauseofaction());
        _params.put("court", _stage.getInfo().getCourt());
        _params.put("case_number", _stage.getInfo().getCasenumber());
        _params.put("claim", _stage.getInfo().getClaim());
        _params.put("remark", "");
        //_params.put("crimename", _stage.getInfo().getCrimename());
        _params.put("crimename", "");
        _params.put("civilrequest", _stage.getInfo().getCivilrequest());

        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String _strDetentiondate = _stage.getInfo().getDetentiondate();
        if (_strDetentiondate != null && !_strDetentiondate.isEmpty()) {
            _params.put("detentiondate", _dataFormat.parse(_strDetentiondate));
        } else {
            _params.put("detentiondate", null);
        }

        String _strArrestdate = _stage.getInfo().getArrestdate();
        if (_strArrestdate != null && !_strArrestdate.isEmpty()) {
            _params.put("arrestdate", _dataFormat.parse(_strArrestdate));
        } else {
            _params.put("arrestdate", null);
        }

        _params.put("custodyplace", _stage.getInfo().getCustodyplace());
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    private ProjectList toProjectList(CrmProject project) {
        ProjectList _project = new ProjectList();
        _project.setRecid(project.getRecid());
        _project.setRecname(project.getRecname());
        _project.setCurrent_stage(project.getCurrent_stage());
        return _project;
    }

    private ProjectClient toProjectClient(CrmProjectClient client) {
        ProjectClient _pc = new ProjectClient();
        _pc.setRecid(client.getRecid());
        _pc.setTitle(client.getTitle());
        _pc.setName(client.getName());
        _pc.setContact(client.getContact());
        _pc.setPhone(client.getPhone());
        _pc.setMail(client.getMail());
        _pc.setRectype(client.getRectype());
        _pc.setClientid(client.getRecid());
        _pc.setTitleid(client.getTitleid());
        _pc.setIsnew(false);
        return _pc;
    }

    private ProjectContact toProjectContract(CrmProjectContact contract) {
        ProjectContact _contact = new ProjectContact();
        _contact.setName(contract.getName());
        _contact.setPhone(contract.getPhone());
        _contact.setRectype(contract.getRectype());
        return _contact;
    }

    private ProjectFile toProjectFile(CrmProjectFile file) {

        ProjectFile _file = new ProjectFile();
        _file.setFileid(file.getRecid());
        String _fileName = file.getFilename();
        _file.setFolderid(file.getFolderid());
        _file.setUploadfileid(file.getUploadfileid());
        _file.setFilename(_fileName);
        _file.setFiletype(file.getFiletype());
        _file.setFoldername(file.getFoldername());
        String _fileSuffix = FilenameUtils.getExtension(_fileName);
        _file.setExtension(_fileSuffix);
        // _file.setShowfilename(file.getShowfilename());

        String _newFileName = file.getUploadfileid();
        if (!_fileSuffix.isEmpty()) {
            _newFileName = _newFileName + "." + _fileSuffix;
        }
        _file.setNewfilename(_newFileName);

        if (file.getIsviewed() == 0) {
            _file.setIsviewed(false);
        } else {
            _file.setIsviewed(true);
        }

        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        _dataFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        String _strBeginTime = _dataFormat.format(file.getUploadtime());

        _file.setUploader(file.getUploader());
        _file.setUploadtime(_strBeginTime);
        _file.setSourcefilename(file.getSourcefilename());

        return _file;
    }

    private ProjectMember toProjectMember(CrmProjectMember member) {
        ProjectMember _member = new ProjectMember();
        _member.setUserid(member.getUserid());
        _member.setUsername(member.getUsername());
        _member.setGroupid(member.getGroupid());
        _member.setIsmanager(member.getIsmanager());
        _member.setGrouptype(member.getGrouptype());
        _member.setInnergrouptype(member.getInnergrouptype());
        _member.setRecid(member.getRecid());
        _member.setIshost(member.ishost());
        //_member.setClientid();
        return _member;
    }

    private List<ProjectMember> toProjectMemberList(List<CrmProjectMember> members) {

        List<ProjectMember> _responseList = new ArrayList<>();
        for (CrmProjectMember _m : members) {
            ProjectMember _responseMember = toProjectMember(_m);
            _responseList.add(_responseMember);
        }
        return _responseList;
    }

    public ProjectChatTopic toProjectChatTopic(CrmProjectChatTopic topic) {
        ProjectChatTopic _topic = new ProjectChatTopic();
        _topic.setTopicid(topic.getTopicid());
        _topic.setTopicname(topic.getTopicname());
        _topic.setStageid(topic.getStageid());
        return _topic;
    }

    public ProjectChatStage toProjectChatStage(CrmProjectChatStage stage) {
        ProjectChatStage _stage = new ProjectChatStage();
        _stage.setStageid(stage.getStageid());
        _stage.setStagename(stage.getStagename());
        return _stage;

    }

    //添加聊天聊天组
    private int insertChatGroup(String groupid, String groupName, String projectid, int stageid, int chatType, int groupType, String relatedid, String prfixName, int userid,String color) {
        int _result = 0;
        String _strSql = " insert into crm_chat_group (recid,recname,objectid,stageid,chattype,grouptype,reccreator,chatstageid,relatedid,prefixname,color) " +
                " values(:recid,:recname,:objectid,:stageid,:chattype,:grouptype,:reccreator,:chatstageid,:relatedid,:prefixname,:color)";

        int _chatstageid = 0;
        //_chatstageid = getMinChatStageid();
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", groupid);
        _params.put("recname", groupName);
        _params.put("objectid", projectid);
        _params.put("stageid", stageid);
        _params.put("chatstageid", _chatstageid);
        _params.put("chattype", chatType);
        _params.put("grouptype", groupType);
        _params.put("reccreator", userid);
        _params.put("relatedid", relatedid);
        _params.put("prefixname", prfixName);
        _params.put("color", color);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    public int addSingleMember(Session session, String projectid, int stageid, String groupid, ProjectMember member, int userid) {
        int _result = 0;
        String strSql = " insert into crm_project_member(recid,projectid,stageid,groupid,userid,ismanager,reccreator,grouptype) " +
                " values(:recid,:projectid,:stageid,:groupid,:userid,:ismanager,:reccreator,:grouptype)";

        Query query = session.createSQLQuery(strSql);
        query.setParameter("recid", UUID.randomUUID().toString());
        query.setParameter("projectid", projectid);
        query.setParameter("stageid", stageid);
        query.setParameter("groupid", groupid);
        query.setParameter("grouptype", member.getGrouptype());
        query.setParameter("innergrouptype", member.getGrouptype());
        query.setParameter("userid", member.getUserid());
        query.setParameter("ismanager", member.getIsmanager());
        query.setParameter("reccreator", userid);
        _result = query.executeUpdate();

        return _result;
    }

    private int insertProjectContact(String projectid, int stageid, int contactType, List<ProjectContact> _fullCount, int userid) {
        int _result = 0;
        int _finalResult = 0;

        String _strSql = " insert into crm_project_contact (recid,projectid,stageid,name,phone,rectype,reccreator)" +
                " values (:recid,:projectid,:stageid,:name,:phone,:rectype,:reccreator)";

        if (_fullCount != null && _fullCount.size() > 0) {
            for (ProjectContact _contact : _fullCount) {

                Map<String, Object> _params = new HashMap<>();
                _params.put("recid", UUID.randomUUID().toString());
                _params.put("projectid", projectid);
                _params.put("stageid", stageid);
                _params.put("name", _contact.getName());
                _params.put("phone", _contact.getPhone());
                _params.put("rectype", contactType);
                _params.put("reccreator", userid);
                _result = updateEntity(_strSql, _params);
                _finalResult += _result;
            }
        }
        return _finalResult;
    }

    //获取项目联系人
    private List<CrmProjectContact> getProjectContact(String projectid, int userid) {
        String _strSql = " select recid,stageid,name,phone,rectype" +
                " from crm_project_contact " +
                " where recstatus=1 " +
                " and  projectid=:projectid  order by createtime desc ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectContact> _contactList = getEntitys(_strSql, _params, CrmProjectContact.class);
        return _contactList;
    }

    private int deleteProjectContact(List<CrmProjectContact> contacts) {
        int _result = 0;
        int _finalResult = 0;
        String _strSql = " update crm_project_contact set recstatus=0 where recid=:recid  ";
        for (CrmProjectContact contact : contacts) {
            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", contact.getRecid());
            _result = updateEntity(_strSql, _params);
            _finalResult += _result;
        }
        return _result;
    }

    private int insertProjectFile(String projectid, int stageid, List<ProjectFile> files, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (ProjectFile _file : files) {
            //根据项目判断当前文件的名称是否重复
            int count = queryFileName(projectid, _file.getFilename());
            if (count > 0) {
                StringBuilder stringBuilder = new StringBuilder(_file.getFilename());
                StringBuilder renName = stringBuilder.insert(stringBuilder.lastIndexOf("."), "(" + count + ")");
                _file.setFilename(renName.toString());
              /*  if (StringUtils.hasText(_file.getSourcefilename())) {
                    JSONObject parse = JSONObject.parseObject(_file.getSourcefilename());
                    parse.put("name", renName.substring(0, renName.lastIndexOf(".")));
                    _file.setSourcefilename(JSON.toJSONString(parse));
                }*/
            }

            String _recid = UUID.randomUUID().toString();
            _result = insertProjectFileBasic(projectid, stageid, _recid, _file, userid);
            _finalResult += _result;

            //回写fileId 用于发消息
            _file.setFileid(_recid);
        }
        return _finalResult;
    }


    private int queryFileName(String projectid, String filename) {
        StringBuilder stringBuilder = new StringBuilder(filename);
        StringBuilder renName = stringBuilder.insert(stringBuilder.lastIndexOf("."), "(%)");
        String strSql = "SELECT COUNT(recid) FROM `crm_project_file` WHERE recstatus = 1 and projectid = :projectid and ( filename = :filename " +
                " or filename LIKE :renName )";
        Map<String, Object> params = new HashMap<>();
        params.put("projectid", projectid);
        params.put("filename", filename);
        params.put("renName", renName.toString());
        return getEntityCount(strSql, params);
    }

    private int insertProjectFileBasic(String projectid, int stageid, String recid, ProjectFile _file, int userid) {
        int _result = 0;

        String _strSql = " insert into crm_project_file(recid,projectid,stageid,folderid,uploadfileid,filename,filetype,reccreator,sourcefilename) " +
                "values(:recid,:projectid,:stageid,:folderid,:uploadfileid,:filename,:filetype,:reccreator,:sourcefilename)";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("folderid", _file.getFolderid());
        _params.put("uploadfileid", _file.getUploadfileid());
        _params.put("filename", _file.getFilename());
        _params.put("filetype", _file.getFiletype());
        _params.put("reccreator", userid);
        _params.put("sourcefilename", _file.getSourcefilename());
        _result = updateEntity(_strSql, _params);

        return _result;
    }

    private List<CrmProjectFile> getProjectFiles(String projectid, int userid) {
        String _strSql = " select recid,stageid,folderid,filename,uploadfileid,filetype,foldername,showfilename,isviewed,uploader,createtime,sourcefilename from (" +
                " select f.recid,f.stageid,f.folderid,f.filename,f.uploadfileid,f.filetype," +
                " CONCAT(coalesce(p.prefixname,''),coalesce(p.recname,'')) as foldername ,coalesce(u.showfilename,'') as showfilename, " +
                "  u2.realname as uploader,f.createtime,f.sourcefilename, " +
                " case  when h.recid is null then false else true end  as isviewed " +
                " from crm_project_file f " +
                " left join crm_project_folder p on f.folderid=p.recid " +
                " left join crm_upload_file u on f.uploadfileid=u.fileid " +
                " left join crm_user u2 on f.reccreator=u2.id " +
                " left join (select * from crm_view_file_history where viewerid=:userid) h on h.filerecid=f.recid " +
                " where f.recstatus=1 " +
                " and  f.projectid=:projectid ) w" +
                " order by w.isviewed asc, w.createtime asc ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        _params.put("userid", userid);
        List<CrmProjectFile> _fileList = getEntitys(_strSql, _params, CrmProjectFile.class);
        return _fileList;
    }

    private int deleteProjectFiles(List<CrmProjectFile> files, int userid) {

        int _result = 0;
        int _finalResult = 0;
        String _strSql = " delete from crm_project_file where recid=:recid ";
        for (CrmProjectFile file : files) {
            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", file.getRecid());
            _result = updateEntity(_strSql, _params);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public int insertProjectMember(String projectid, int stageid, String groupid, List<ProjectMember> members, int userid) {

        int _result = 0;
        int _finalResult = 0;

        String _strSql = " insert into crm_project_member(recid,projectid,stageid,groupid,userid,ismanager,reccreator,grouptype,innergrouptype,ishost,recorder) " +
                " values(:recid,:projectid,:stageid,:groupid,:userid,:ismanager,:reccreator,:grouptype,:innergrouptype,:ishost,:recorder)";

        String _maxSql = " select coalesce(max(recorder),0) from crm_project_member where projectid=:projectid and stageid=:stageid and grouptype=:grouptype ";
        Map<String, Object> _paramsMax = new HashMap<>();
        for (ProjectMember _member : members) {

            _paramsMax.clear();
            _paramsMax.put("projectid", projectid);
            _paramsMax.put("stageid", stageid);
            _paramsMax.put("grouptype", _member.getGrouptype());

            if (_member.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()) {
                _maxSql += " and innergrouptype=:innergrouptype ";
                _paramsMax.put("innergrouptype", _member.getInnergrouptype());
            }
            int _recOrder = getMax(_maxSql, _paramsMax);


            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", UUID.randomUUID().toString());
            _params.put("projectid", projectid);
            _params.put("stageid", stageid);
            _params.put("groupid", groupid);
            _params.put("userid", _member.getUserid());
            _params.put("ismanager", _member.getIsmanager());
            _params.put("ishost", _member.getIshost());
            _params.put("reccreator", userid);
            _params.put("grouptype", _member.getGrouptype());
            _params.put("innergrouptype", _member.getInnergrouptype());
            _params.put("recorder", _recOrder + 1);

            _result = updateEntity(_strSql, _params);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public int insertProjectMemberSingle(String projectid, int stageid, String groupid, ProjectMember _member, String relatedid, int userid) {
        int _result = 0;
        String _strSql = " insert into crm_project_member(recid,projectid,stageid,groupid,userid,ismanager,reccreator,grouptype,innergrouptype,relatedid,ishost,recorder) " +
                " values(:recid,:projectid,:stageid,:groupid,:userid,:ismanager,:reccreator,:grouptype,:innergrouptype,:relatedid,:ishost,:recorder)";


        String _maxSql = " select coalesce(max(recorder),0) from crm_project_member where projectid=:projectid and stageid=:stageid and grouptype=:grouptype ";
        Map<String, Object> _paramsMax = new HashMap<>();
        _paramsMax.put("projectid", projectid);
        _paramsMax.put("stageid", stageid);
        _paramsMax.put("grouptype", _member.getGrouptype());

        if (_member.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()) {
            _maxSql += " and innergrouptype=:innergrouptype ";
            _paramsMax.put("innergrouptype", _member.getInnergrouptype());
        }
        int _recOrder = getMax(_maxSql, _paramsMax);


        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", UUID.randomUUID().toString());
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("groupid", groupid);
        _params.put("userid", _member.getUserid());
        _params.put("ismanager", _member.getIsmanager());
        _params.put("reccreator", userid);
        _params.put("grouptype", _member.getGrouptype());
        _params.put("innergrouptype", _member.getInnergrouptype());
        _params.put("relatedid", relatedid);
        _params.put("ishost", _member.getIshost());
        _params.put("recorder", _recOrder + 1);

        _result = updateEntity(_strSql, _params);
        return _result;
    }

    public int insertProjectMemberBatch(String projectid, int stageid, String groupid, List<ProjectMember> members, String relatedid, int userid) {

        int _result = 0;
        int _finalResult = 0;
        for (ProjectMember _member : members) {
            _result = insertProjectMemberSingle(projectid, stageid, groupid, _member, relatedid, userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public List<CrmProjectMember> getProjectMember(String projectid, int userid) {

        //团队成员
        String _strSql = " select recid,stageid,groupid,userid,u.realname as username,ismanager,grouptype,innergrouptype,relatedid,ishost,projectid " +
                " from crm_project_member m " +
                " inner join crm_user u on m.userid=u.id " +
                " where m.recstatus=1 " +
                " and  projectid=:projectid" +
                " order by m.recorder asc ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectMember> _memberList = getEntitys(_strSql, _params, CrmProjectMember.class);
        return _memberList;
    }

    public int deleteProjectMember(List<CrmProjectMember> members, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (CrmProjectMember _m : members) {
            _result = deleteProjectMemberSingle(_m, userid);
        }
        _finalResult += _result;
        return _finalResult;
    }

    public int deleteProjectMemberSingle(CrmProjectMember member, int userid) {
        int _result = 0;
        String _strSql = " update  crm_project_member set recstatus=0 where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", member.getRecid());
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    //获取需要新增的member
    private List<ProjectMember> getAddProjectMember(List<ProjectMember> newMember, List<CrmProjectMember> oldMember) {
        boolean _userIsExist = false;
        List<ProjectMember> _addMembers = new ArrayList<>();
        for (ProjectMember member : newMember) {
            _userIsExist = false;
            long _theCount = oldMember.stream().filter(x -> x.getUserid() == member.getUserid()).count();
            if (_theCount > 0) {
                _userIsExist = true;
            }
            if (!_userIsExist) {
                _addMembers.add(member);
            }
        }
        return _addMembers;
    }

    //获取需要删除的member
    private List<CrmProjectMember> getDeleteProjectMember(List<ProjectMember> newMember, List<CrmProjectMember> oldMember) {

        boolean _userIsExist = false;
        List<CrmProjectMember> _deleteMembers = new ArrayList<>();
        for (CrmProjectMember m : oldMember) {
            _userIsExist = false;
            for (ProjectMember member : newMember) {
                if (m.getUserid() == member.getUserid()) {
                    _userIsExist = true;
                    break;
                }
            }
            if (!_userIsExist) {
                _deleteMembers.add(m);
            }
        }
        return _deleteMembers;
    }

    private List<Integer> toMemberIds(List<ProjectMember> members) {
        List<Integer> _memberIds = new ArrayList<>();
        for (ProjectMember m : members) {
            _memberIds.add(m.getUserid());
        }
        return _memberIds;
    }

    private List<Integer> toMemberIdsFromCrm(List<CrmProjectMember> members) {
        List<Integer> _memberIds = new ArrayList<>();
        for (CrmProjectMember m : members) {
            _memberIds.add(m.getUserid());
        }
        return _memberIds;
    }

    private List<CrmProjectStageRelate> getProjectStageRelate(String projectid) {

        String _strSql = " select recid,stageid,stagestatus,completedtime,createtime,projectid " +
                " from crm_project_stage_relate " +
                " where recstatus=1 " +
                " and  projectid=:projectid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectStageRelate> _stageRelates = getEntitys(_strSql, _params, CrmProjectStageRelate.class);
        return _stageRelates;
    }

    //删除老数据
    private int deleteProjectStageRelate(List<CrmProjectStageRelate> stageRelates) {

        int _result = 0;
        int _finalResult = 0;
        String _strSql = " update crm_project_stage_relate set recstatus=0 where recid=:recid ";
        for (CrmProjectStageRelate _relate : stageRelates) {
            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", _relate.getRecid());
            _result = updateEntity(_strSql, _params);
            _finalResult += _result;
        }
        return _finalResult;
    }

    private int insertProjectStageRelate(String projectid, int stageid, int recorder, int userid) {

        int _result = 0;
        //添加新数据
        String _strSql =
                " insert into crm_project_stage_relate(recid,projectid,stageid,recorder,reccreator)" +
                        " values(:recid,:projectid,:stageid,:recorder,:reccreator) ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", UUID.randomUUID().toString());
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("recorder", recorder);
        _params.put("reccreator", userid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    private int insertProjectInfo(String projectid, ProjectStage stage, int userid) {
        int _result = 0;

        //添加 基本信息
        String _strSql =
                " insert into crm_project_info(recid,projectid,stageid,cause_of_action,court,case_number,claim,remark)" +
                        " values(:recid,:projectid,:stageid,:cause_of_action,:court,:case_number,:claim,:remark)";

        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", UUID.randomUUID().toString());
        _params.put("projectid", projectid);
        _params.put("stageid", stage.getStageid());
        _params.put("cause_of_action", stage.getInfo().getCauseofaction());
        _params.put("court", stage.getInfo().getCourt());
        _params.put("case_number", stage.getInfo().getCasenumber());
        _params.put("claim", stage.getInfo().getClaim());
        _params.put("remark", "");
        _result = updateEntity(_strSql, _params);

        return _result;
    }

    private int projectMemmberEdit(String _projectid, int _stageid, List<ProjectMember> _membersRequest, List<CrmProjectMember> oldMemberList, int userId) {

        //添加新用户
        //同一个阶段下，同一个分组的，是否存在该用户
        //  List<ProjectMember> _membersRequest = _stage.getMembers();
        int _groupType1 = BaseEnum.GroupType.Client.getGroupType();
        int _groupType2 = BaseEnum.GroupType.Lawyer.getGroupType();
        int _innerGroupType1 = BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType();
        int _innerGroupType2 = BaseEnum.InnerGroupType.LawyerGroup.getInnerGroupType();


        List<ProjectMember> _newMember1 = new ArrayList<>();
        List<ProjectMember> _newMember2 = new ArrayList<>();
        List<ProjectMember> _newMember3 = new ArrayList<>();
        for (ProjectMember member : _membersRequest) {

            if (member.getGrouptype() == _groupType1 && member.getInnergrouptype() == _innerGroupType1) {
                _newMember1.add(member);
            }
            if (member.getGrouptype() == _groupType1 && member.getInnergrouptype() == _innerGroupType2) {
                _newMember2.add(member);
            }
            if (member.getGrouptype() == _groupType2) {
                _newMember3.add(member);
            }
        }

        List<CrmProjectMember> _oldMember1 = new ArrayList<>();
        List<CrmProjectMember> _oldMember2 = new ArrayList<>();
        List<CrmProjectMember> _oldMember3 = new ArrayList<>();

        List<CrmChatGroupPart> _groupList = getProjectChatGroup(_projectid);
        List<CrmChatGroupPart> _group1 = _groupList.stream().filter(x -> x.getStageid() == _stageid && x.getGrouptype() == _groupType1).collect(Collectors.toList());
        List<CrmChatGroupPart> _group2 = _groupList.stream().filter(x -> x.getStageid() == _stageid && x.getGrouptype() == _groupType2).collect(Collectors.toList());

        String _groupid1 = "";
        if (_group1 != null && _group1.size() > 0) {
            _groupid1 = _group1.get(0).getGroupid();
        }

        String _groupid2 = "";
        if (_group2 != null && _group2.size() > 0) {
            _groupid2 = _group2.get(0).getGroupid();
        }

        for (CrmProjectMember _oldMember : oldMemberList) {
            if (_oldMember.getStageid() == _stageid && _oldMember.getGrouptype() == _groupType1 && _oldMember.getInnergrouptype() == _innerGroupType1) {
                _oldMember1.add(_oldMember);
                _groupid1 = _oldMember.getGroupid();
            }

            if (_oldMember.getStageid() == _stageid && _oldMember.getGrouptype() == _groupType1 && _oldMember.getInnergrouptype() == _innerGroupType2) {
                _oldMember2.add(_oldMember);
                _groupid1 = _oldMember.getGroupid();
            }

            if (_oldMember.getStageid() == _stageid && _oldMember.getGrouptype() == _groupType2) {
                _oldMember3.add(_oldMember);
                _groupid2 = _oldMember.getGroupid();
            }
        }

        // _oldMember3 = oldMemberList.stream().filter(x -> x.getStageid() == _stageid && x.getGrouptype() == _groupType2).collect(Collectors.toList());


        //删除去掉的用户
        List<CrmProjectMember> _deleteMember1 = getDeleteProjectMember(_newMember1, _oldMember1);
        List<CrmProjectMember> _deleteMember2 = getDeleteProjectMember(_newMember2, _oldMember2);
        List<CrmProjectMember> _deleteMember3 = getDeleteProjectMember(_newMember3, _oldMember3);
        if (_deleteMember1.size() > 0) {
            deleteProjectMember(_deleteMember1, userId);
        }
        if (_deleteMember2.size() > 0) {
            deleteProjectMember(_deleteMember2, userId);
        }
        if (_deleteMember3.size() > 0) {
            deleteProjectMember(_deleteMember3, userId);
        }

        //需要添加的用户
        List<ProjectMember> _addMember1 = getAddProjectMember(_newMember1, _oldMember1);
        List<ProjectMember> _addMember2 = getAddProjectMember(_newMember2, _oldMember2);
        List<ProjectMember> _addMember3 = getAddProjectMember(_newMember3, _oldMember3);
        if (_addMember1.size() > 0) {
            insertProjectMember(_projectid, _stageid, _groupid1, _addMember1, userId);
        }
        if (_addMember2.size() > 0) {
            insertProjectMember(_projectid, _stageid, _groupid1, _addMember2, userId);
        }

        if (_addMember3.size() > 0) {
            insertProjectMember(_projectid, _stageid, _groupid2, _newMember3, userId);
        }

        //添加member到im group
        boolean _addMemberToIM = false;
        List<Integer> _addMemberId = toMemberIds(_addMember1);
        if (_addMember1.size() > 0) {
            _addMemberToIM = _imService.addIMGroupMember(_groupid1, _addMemberId, userId);
            if (_addMemberToIM) {
                System.out.println("add to im group success 1");
            }
        }


        if (_addMember2.size() > 0) {
            _addMemberId = toMemberIds(_addMember2);
            _addMemberToIM = _imService.addIMGroupMember(_groupid1, _addMemberId, userId);
            if (_addMemberToIM) {
                System.out.println("add to im group success 2");
            }
        }

        if (_addMember3.size() > 0) {
            _addMemberId = toMemberIds(_addMember3);
            _addMemberToIM = _imService.addIMGroupMember(_groupid2, _addMemberId, userId);
            if (_addMemberToIM) {
                System.out.println("add to im group success 3");
            }
        }


        boolean _deleteMemberFromIM = false;
        List<Integer> _deleteMemberIds = toMemberIdsFromCrm(_deleteMember1);
        if (_deleteMember1.size() > 0) {
            _deleteMemberFromIM = _imService.removeIMGroupMember(_groupid1, _deleteMemberIds, userId);
            if (_deleteMemberFromIM) {
                System.out.println("delete from  im group success 1");
            }
        }

        if (_deleteMember2.size() > 0) {
            _deleteMemberIds = toMemberIdsFromCrm(_deleteMember2);
            _deleteMemberFromIM = _imService.removeIMGroupMember(_groupid1, _deleteMemberIds, userId);
            if (_deleteMemberFromIM) {
                System.out.println("delete from  im group success 2");
            }
        }

        if (_deleteMember3.size() > 0) {
            _deleteMemberIds = toMemberIdsFromCrm(_deleteMember3);
            _deleteMemberFromIM = _imService.removeIMGroupMember(_groupid2, _deleteMemberIds, userId);
            if (_deleteMemberFromIM) {
                System.out.println("delete from  im group success 3");
            }
        }

        return 1;
    }

    //获取项目聊天组
    public List<CrmChatGroupPart> getProjectChatGroup(String projectid) {

        String _strSql = "select recid,recname,objectid,stageid,chattype,grouptype,relatedid,prefixname,chatstageid,topicname " +
                " from crm_chat_group g " +
                " inner join  (select recid as projectid, recname as topicname from crm_project where recstatus = 1) p on g.objectid=p.projectid " +
                " where recstatus=1 " +
                " and  chattype=0 " +
                " and  objectid=:objectid  ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("objectid", projectid);
        List<CrmChatGroupPart> _list = getEntitys(_strSql, _params, CrmChatGroupPart.class);
        return _list;
    }

    //获取项目或者任务聊天组
    public List<CrmChatGroupPart> getChatGroupByGroupId(String groupid) {

        String _strSql = "select recid,recname,objectid,stageid,chattype,grouptype,relatedid,prefixname,chatstageid,topicname " +
                " from crm_chat_group g " +
                " inner join  (select recid as projectid, recname as topicname from crm_project where recstatus = 1) p on g.objectid=p.projectid " +
                " where recstatus=1 and  chattype=0 and  recid=:recid  " +
                " union " +
                " select recid,recname,objectid,stageid,chattype,grouptype,relatedid,prefixname,chatstageid,topicname " +
                " from crm_chat_group g " +
                " inner join (select recid as taskid, content as topicname from crm_task where recstatus = 1)  p on g.objectid=p.taskid" +
                " where recstatus=1 and chattype=1 and  recid=:recid  ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", groupid);
        List<CrmChatGroupPart> _list = getEntitys(_strSql, _params, CrmChatGroupPart.class);
        return _list;
    }

    public int updateProjectChatGroupName(String recid, String prefixName) {

        int _result = 0;
        String _strSql = " update crm_chat_group set prefixname=:prefixname where recid=:recid  ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _params.put("prefixname", prefixName);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    public int updateProjectChatGroupNameBatch(List<CrmChatGroupPart> groups, String prfixName, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (CrmChatGroupPart _g : groups) {
            _result = updateProjectChatGroupName(_g.getGroupid(), prfixName);
            _finalResult += _result;
        }
        return _finalResult;
    }


    @Transactional
    public int deleteProjectStage(ProjectStageDeleteRequest _request, int userid) {
        int _result = 0;


        String projectid = _request.getProjectid();
        int stageid = _request.getStageid();

        String _strSql = "";


        //1.项目阶段
        List<CrmProjectStageRelate> _projectStages = getProjectStageRelate(projectid);
        List<CrmProjectStageRelate> _currentStage = _projectStages.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());

        _result = deleteProjectStageRelate(_currentStage);

        //2.基本信息
        List<CrmProjectInfo> _projectInfos = getProjectInfo(projectid);
        List<CrmProjectInfo> _currentProjectInfo = _projectInfos.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
        deleteProjectInfo(_currentProjectInfo);

        //3.委托人,当事人
        List<CrmProjectClient> _projectClient = getProjectClient(projectid);
        List<CrmProjectClient> _currentProjectClient = _projectClient.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
        deleteProjectClientBatch(_currentProjectClient);

        //4.书记员,合议庭
        List<CrmProjectContact> _projectContactList = getProjectContact(projectid, userid);
        List<CrmProjectContact> _currentProjectContact = _projectContactList.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
        deleteProjectContact(_currentProjectContact);

        //5.文件夹
        List<CrmProjectFolder> _folders = getProjectFolder(projectid, userid);
        if (_folders != null) {
            List<CrmProjectFolder> _stageFolders = _folders.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
            if (_stageFolders != null) {
                deleteProjectFolderBatch(_stageFolders, userid);
            }
        }

        //6.文件
        List<CrmProjectFile> _projectFileList = getProjectFiles(projectid, userid);
        List<CrmProjectFile> _currentProjectFile = _projectFileList.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
        deleteProjectFiles(_currentProjectFile, userid);


        //7.任务
        List<CrmProjectTask> _tasks = getProjectTask(projectid);
        List<CrmProjectTask> _stageTasks = _tasks.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
        for (CrmProjectTask t : _stageTasks) {
            deleteTask(t.getTaskid());
        }

        //8.成员
        List<CrmProjectMember> _memberList = getProjectMember(projectid, userid);
        List<CrmProjectMember> _currentProjectMember = _memberList.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
        if (_currentProjectMember.size() > 0) {
            deleteProjectMember(_currentProjectMember, userid);
        }

        List<CrmProjectMember> _oldMember1 = new ArrayList<>();
        List<CrmProjectMember> _oldMember2 = new ArrayList<>();
        List<CrmProjectMember> _oldMember3 = new ArrayList<>();

        int _groupType1 = BaseEnum.GroupType.Client.getGroupType();
        int _groupType2 = BaseEnum.GroupType.Lawyer.getGroupType();
        int _innerGroupType1 = BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType();
        int _innerGroupType2 = BaseEnum.InnerGroupType.LawyerGroup.getInnerGroupType();

        String _groupid1 = "";
        String _groupid2 = "";
        for (CrmProjectMember _oldMember : _memberList) {
            if (_oldMember.getStageid() == stageid && _oldMember.getGrouptype() == _groupType1 && _oldMember.getInnergrouptype() == _innerGroupType1) {
                _oldMember1.add(_oldMember);
                _groupid1 = _oldMember.getGroupid();
            }

            if (_oldMember.getStageid() == stageid && _oldMember.getGrouptype() == _groupType1 && _oldMember.getInnergrouptype() == _innerGroupType2) {
                _oldMember2.add(_oldMember);
                _groupid1 = _oldMember.getGroupid();
            }

            if (_oldMember.getStageid() == stageid && _oldMember.getGrouptype() == _groupType2) {
                _oldMember3.add(_oldMember);
                _groupid2 = _oldMember.getGroupid();
            }
        }

        //delete chat group
        if (!_groupid1.isEmpty()) {
            deleteProjectChatGroup(_groupid1);
            _imService.destroyIMGroup(_groupid1, userid);
        }

        if (!_oldMember2.isEmpty()) {
            deleteProjectChatGroup(_groupid2);
            _imService.destroyIMGroup(_groupid2, userid);
        }


        boolean _deleteMemberFromIM = false;
        List<Integer> _deleteMemberIds = toMemberIdsFromCrm(_oldMember1);
        if (_oldMember1.size() > 0) {
            _deleteMemberFromIM = _imService.removeIMGroupMember(_groupid1, _deleteMemberIds, userid);
            if (_deleteMemberFromIM) {
                System.out.println("delete from  im group success 1");
            }
        }

        if (_oldMember2.size() > 0) {
            _deleteMemberIds = toMemberIdsFromCrm(_oldMember2);
            _deleteMemberFromIM = _imService.removeIMGroupMember(_groupid1, _deleteMemberIds, userid);
            if (_deleteMemberFromIM) {
                System.out.println("delete from  im group success 2");
            }
        }

        if (_oldMember3.size() > 0) {
            _deleteMemberIds = toMemberIdsFromCrm(_oldMember3);
            _deleteMemberFromIM = _imService.removeIMGroupMember(_groupid2, _deleteMemberIds, userid);
            if (_deleteMemberFromIM) {
                System.out.println("delete from  im group success 3");
            }
        }

        return _result;
    }

    //1.删除project基本信息

    private int deleteProjectInfo(List<CrmProjectInfo> infos) {

        int _result = 0;
        int _finalResult = 0;
        String _strSql = " update crm_project_info set recstatus=0 where recid=:recid";
        Map<String, Object> _params = new HashMap<>();
        for (CrmProjectInfo info : infos) {
            _params.clear();
            _params.put("recid", info.getRecid());
            _result = updateEntity(_strSql, _params);
            _finalResult += _result;
        }
        return _finalResult;
    }

    //获取项目任务
    public List<CrmProjectTask> getProjectTask(String projectid) {

        String _strSql =
                " select pt.recid,pt.projectid,pt.stageid,pt.taskid, " +
                        " t.recname as taskname, t.content,t.begintime,t.taskstatus,t.reccreator " +
                        " from crm_project_task pt " +
                        " inner join crm_task t on pt.taskid=t.recid " +
                        " where pt.recstatus=1" +
                        " and  projectid=:projectid " +
                        " and taskstatus!=2 " +
                        " order by t.begintime asc ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectTask> _tasks = getEntitys(_strSql, _params, CrmProjectTask.class);

        String _strSql1 =
                " select pt.recid,pt.projectid,pt.stageid,pt.taskid, " +
                        " t.recname as taskname, t.content,t.begintime,t.taskstatus,t.reccreator " +
                        " from crm_project_task pt " +
                        " inner join crm_task t on pt.taskid=t.recid " +
                        " where pt.recstatus=1" +
                        " and  projectid=:projectid " +
                        " and taskstatus=2 " +
                        " order by t.completetime desc ";

        List<CrmProjectTask> _tasks1 = getEntitys(_strSql1, _params, CrmProjectTask.class);
        _tasks.addAll(_tasks1);
        return _tasks;
    }

    public List<CrmProjectTask> getProjectTaskSingle(Session session, String projectid, int stageid, String taskid) {

        String _strSql =
                " select pt.recid,pt.projectid,pt.stageid,pt.taskid, " +
                        " t.recname as taskname, t.content,t.begintime,t.taskstatus,t.reccreator " +
                        " from crm_project_task pt " +
                        " inner join crm_task t on pt.taskid=t.recid " +
                        " where pt.recstatus=1 " +
                        " and  pt.projectid=:projectid " +
                        " and pt.stageid=:stageid " +
                        " and pt.taskid=:taskid ";

        NativeQuery _selectQuery = session.createSQLQuery(_strSql);
        _selectQuery.setParameter("projectid", projectid);
        _selectQuery.setParameter("stageid", stageid);
        _selectQuery.setParameter("taskid", taskid);
        List<CrmProjectTask> _tasks = _selectQuery.addEntity(CrmProjectTask.class).list();
        return _tasks;
    }

    public int insertProjectTask(String projectid, int stageid, String taskid, int userid) {

        String _strSql =
                " insert into crm_project_task(recid,projectid,stageid,taskid,reccreator) " +
                        " values(:recid,:projectid,:stageid,:taskid,:reccreator)  ";

        String _recid = UUID.randomUUID().toString();
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", _recid);
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("taskid", taskid);
        _params.put("reccreator", userid);
        int _result = updateEntity(_strSql, _params);

        return _result;
    }

    public int insertProjectTasks(String projectid, int stageid, List<ProjectTask> tasks, int userid) {

        int _result = 0;
        int _finalResult = 0;

        for (ProjectTask _task : tasks) {
            _result = insertProjectTask(projectid, stageid, _task.getTaskid(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public int deleteProjectTask(String recid) {
        int _result = 0;
        String _strSql = " update crm_project_task set recstatus=0 where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    private int deleteProjectTasks(List<CrmProjectTask> tasks) {

        int _result = 0;
        int _finalResult = 0;

        for (CrmProjectTask task : tasks) {
            _result = deleteProjectTask(task.getRecid());
            _finalResult += _result;
        }
        return _finalResult;
    }

    private ProjectTask toProjectTask(CrmProjectTask task) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String _strBeginTime = sdf.format(task.getTaskbegintime());

        ProjectTask _task = new ProjectTask();
        _task.setRecid(task.getRecid());
        _task.setStageid(task.getStageid());
        _task.setTaskid(task.getTaskid());
        _task.setTaskname(task.getTaskname());
        _task.setTaskcontent(task.getTaskcontent());
        _task.setBegintime(_strBeginTime);

        _task.setTaskstatus(task.getTaskstatus());

        int _taskStatus = task.getTaskstatus();
        if (_taskStatus == BaseEnum.TaskStatus.Complete.getTaskStatus()) {
            _task.setIscompleted(true);
        } else {
            _task.setIscompleted(false);
        }

        _task.setTaskcreator(task.getTaskcreator());
        return _task;

    }

    public int insertProjectRemarkViewers(String projectid, int stageid, String remarkid, List<ProjectInfoRemarkViewer> viewers, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (ProjectInfoRemarkViewer viewer : viewers) {
            _result = insertProjectRemarkViewer(projectid, stageid, remarkid, viewer.getUserid(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public int insertProjectRemarkViewer(String projectid, int stageid, String remarkid, int viewerid, int userid) {
        int _result = 0;


        String _strSql = " select count(1) from crm_project_remark_viewer " +
                " where recstatus=1 " +
                " and  projectid=:projectid " +
                " and stageid=:stageid " +
                " and  userid=:userid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("userid", viewerid);

        int _theCount = getEntityCount(_strSql, _params);
        if (_theCount > 0) {
            _result = 0;
            return _result;
        }


        _strSql = " insert into crm_project_remark_viewer " +
                " (recid,projectid,stageid,userid,reccreator,remarkid) " +
                " values(:recid,:projectid,:stageid,:userid,:reccreator,:remarkid) ";

        _params.clear();
        //Map<String, Object> _params = new HashMap<>();
        _params.put("recid", UUID.randomUUID().toString());
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("userid", viewerid);
        _params.put("reccreator", userid);
        _params.put("remarkid", remarkid);
        _result = updateEntity(_strSql, _params);

        return _result;
    }

    public List<CrmProjectInfoRemarkViewer> getProjectRemarkViewer(String projectid, int userid) {

        String _strSql =
                " select v.recid,v.userid,u.realname as username,v.stageid,v.remarkid,v.reccreator,u.headimage" +
                        " from crm_project_remark_viewer v " +
                        " inner join crm_user u on v.userid=u.id " +
                        " where u.recstatus=1 " +
                        " and  v.recstatus=1 " +
                        " and  v.projectid=:projectid " +
                        " order by v.createtime asc";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        return getEntitys(_strSql, _params, CrmProjectInfoRemarkViewer.class);
    }


    public int deleteProjectRemarkViewer(String recid) {

        int _result = 0;
        String _strSql = " update crm_project_remark_viewer set recstatus=0 where recid=:recid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }


    public int deleteProjectRemarkViewers(List<CrmProjectInfoRemarkViewer> viewers) {
        int _result = 0;
        int _finalResult = 0;
        for (CrmProjectInfoRemarkViewer viewer : viewers) {

            _result = deleteProjectRemarkViewer(viewer.getRecid());
            _finalResult += _result;
        }
        return _finalResult;
    }

    private ProjectInfoRemarkViewer toProjectInfoRemarkViewer(CrmProjectInfoRemarkViewer viewer) {

        ProjectInfoRemarkViewer _viewer = new ProjectInfoRemarkViewer();
        _viewer.setUserid(viewer.getUserid());
        _viewer.setUsername(viewer.getUsername());
        _viewer.setRecid(viewer.getRecid());
        _viewer.setHeadimage(viewer.getHeadimage());
        return _viewer;
    }

    private List<ProjectInfoRemarkViewer> toProjectInfoRemarkViewers(List<CrmProjectInfoRemarkViewer> viewers) {
        List<ProjectInfoRemarkViewer> _viewers = new ArrayList<>();
        for (CrmProjectInfoRemarkViewer _viewer : viewers) {
            _viewers.add(toProjectInfoRemarkViewer(_viewer));
        }
        return _viewers;
    }

    private int insertProjectRemark(String projectid, int stageid, String recid, String content, int userid) {
        int _result = 0;

        try {
            String _strSql = " insert into crm_project_remark " +
                    " (recid,projectid,stageid,content,reccreator) " +
                    " values(:recid,:projectid,:stageid,:content,:reccreator) ";

            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", recid);
            _params.put("projectid", projectid);
            _params.put("stageid", stageid);
            _params.put("content", content);
            _params.put("reccreator", userid);
            _result = updateEntity(_strSql, _params);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    public List<CrmProjectRemark> getProjectRemark(String projectid, int userid) {

        String _strSql =
                " select r.recid,r.stageid,r.content,r.reccreator,COALESCE(u.realname,'') as username" +
                        " from crm_project_remark r " +
                        " inner join crm_user u on r.reccreator=u.id " +
                        "  where r.recstatus=1 " +
                        " and  r.projectid=:projectid " +
                        " order by r.createtime desc  ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        return getEntitys(_strSql, _params, CrmProjectRemark.class);

    }

    private int updateProjectRemark(String recid, String content, int userid) {
        int _result = 0;

        try {
            String _strSql = " update  crm_project_remark  set content=:content where recid=:recid ";

            Map<String, Object> _params = new HashMap<>();
            _params.put("recid", recid);
            _params.put("content", content);
            _result = updateEntity(_strSql, _params);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    private int deleteProjectRemark(String recid, int userid) {
        int _result = 0;
        String _strSql = " update  crm_project_remark  set recstatus=0  where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _result = updateEntity(_strSql, _params);

        return _result;
    }

    private int deleteProjectRemarks(List<CrmProjectRemark> _remarks, int userid) {

        int _result = 0;
        int _finalResult = 0;
        for (CrmProjectRemark _remark : _remarks) {
            _result = deleteProjectRemark(_remark.getRecid(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    private ProjectRemark toProjectRemark(CrmProjectRemark remark) {

        ProjectRemark _remark = new ProjectRemark();
        _remark.setRecid(remark.getRecid());
        _remark.setContent(remark.getContent());
        _remark.setCreatorname(remark.getUsername());
        _remark.setCreatorid(remark.getReccreator());
        return _remark;
    }

    //获取创建文件夹的模板文件夹名称
    public List<CrmProjectBasicFolder> getProjectBasicFolder(int projectType) {

        String _strSql = " select recid,recname,projecttype,rectype,innerfoldertype,foldertype,replaceable " +
                " from crm_project_default_folder " +
                " where recstatus=1 " +
                " and projecttype=:projecttype ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projecttype", projectType);
        List<CrmProjectBasicFolder> _list = getEntitys(_strSql, _params, CrmProjectBasicFolder.class);
        return _list;
    }

    public int insertProjectFolder(String projectid, int stageid, String folderName, int folderType, String relatedid, String prefixname, int innerfoldertype, boolean islawyerfolder, int userid) {

        int _result = 0;
        String _recid = UUID.randomUUID().toString();
        _result = insertProjectFolderBasic(projectid, stageid, _recid, folderName, folderType, relatedid, prefixname, innerfoldertype, islawyerfolder, userid);
        return _result;
    }

    public int insertProjectFolderBasic(String projectid, int stageid, String folderid, String folderName, int folderType, String relatedid, String prefixname, int innerfoldertype, boolean islawyerfolder, int userid) {


        int _result = 0;
        String _strSql = " insert into crm_project_folder(recid,recname,projectid,stageid,reccreator,foldertype,relatedid,prefixname,innerfoldertype,islawyerfolder) " +
                "  values(:recid,:recname,:projectid,:stageid,:reccreator,:foldertype,:relatedid,:prefixname,:innerfoldertype,:islawyerfolder) ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", folderid);
        _params.put("recname", folderName);
        _params.put("projectid", projectid);
        _params.put("stageid", stageid);
        _params.put("reccreator", userid);
        _params.put("foldertype", folderType);
        _params.put("relatedid", relatedid);
        _params.put("prefixname", prefixname);
        _params.put("innerfoldertype", innerfoldertype);
        _params.put("islawyerfolder", islawyerfolder);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    public List<CrmProjectStageName> getProjectStageName(int projectType) {

        String _strSql = " select recid,recname from crm_project_stage " +
                " where projecttype=:projecttype ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projecttype", projectType);
        return getEntitys(_strSql, _params, CrmProjectStageName.class);
    }

    private void insertProjectFolderForClient(String projectid, int stageid, String folderName, int folderType, List<CrmProjectBasicFolder> folders, String clientRecid, String prefixname, int userid) {
        String _realFolderName = "";
        for (CrmProjectBasicFolder _folder : folders) {
            _realFolderName = folderName + _folder.getRecname();
            int _innerFolderType = _folder.getInnerfoldertype();

            boolean _isLawyerFolder = false;
            if (_folder.getFoldertype() == 1) {
                _isLawyerFolder = true;
            }

            insertProjectFolder(projectid, stageid, _realFolderName, folderType, clientRecid, prefixname, _innerFolderType, _isLawyerFolder, userid);
        }
    }

    public List<CrmProjectFolder> getProjectFolder(String projectid, int userid) {

        String _strSql = " select recid,recname,stageid,foldertype,relatedid,reccreator,prefixname,innerfoldertype,islawyerfolder " +
                " from crm_project_folder " +
                " where recstatus=1 " +
                " and projectid=:projectid " +
                " order by islawyerfolder desc";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectFolder> _list = getEntitys(_strSql, _params, CrmProjectFolder.class);
        return _list;
    }

    public int deleteProjectFolder(String recid, int userid) {
        int _result = 0;
        String _strSql = " update crm_project_folder set recstatus=0 where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    public int deleteProjectFolderBatch(List<CrmProjectFolder> folders, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (CrmProjectFolder _f : folders) {
            _result = deleteProjectFolder(_f.getRecid(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public int updateProjectFolderName(String recid, String prefixname) {

        int _result = 0;
        String _strSql = " update crm_project_folder set prefixname=:prefixname  where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _params.put("prefixname", prefixname);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    public int updateProjectFolderNameBatch(List<CrmProjectFolder> folders, String prfixName, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (CrmProjectFolder _f : folders) {
            _result = updateProjectFolderName(_f.getRecid(), prfixName);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public List<CrmChatGroup> getProjectGroup(Session session, String projectid) {

        String strSql = " select recid,recname,objectid,chattype,stageid,chatstageid,grouptype,relatedid,prefixname,isactive,createtime" +
                " from crm_chat_group " +
                " where relatedid=:relatedid ";

        List<CrmChatGroup> _list = new ArrayList<>();
        NativeQuery _query = session.createSQLQuery(strSql);
        _query.setParameter("projectid", projectid);
        _list = _query.addEntity(CrmChatGroup.class).list();

        return _list;
    }

    //获取项目聊天组
    public int deleteProjectChatGroup(String recid) {

        String _strSql = " update crm_chat_group set recstatus=0 where recid=:recid  ";
        int _result = 0;
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    public int deleteProjectChatGroupBatch(List<CrmChatGroupPart> groups, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (CrmChatGroupPart _g : groups) {
            _result = deleteProjectChatGroup(_g.getGroupid());

            //destroy im group
            _imService.destroyIMGroup(_g.getGroupid(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public List<CrmProjectStage> getProjectStageList(String projectid) {
        return getProjectStageList(projectid, "projct");

    }

    public List<CrmProjectStage> getProjectStageList(String projectid, String forType) {

        String _strSql =
                "select s.recid,s.recname,sr.recorder,s.datastageid,stagetype," +
                        " case when sr.stagestatus=2 then true else false end  as iscomplete " +
                        " from crm_project_stage s " +
                        " inner join crm_project_stage_relate sr on s.recid=sr.stageid " +
                        " where sr.recstatus=1 ";

        //过滤掉已经完成的阶段
        if (forType == "task") {
            _strSql += " and  sr.stagestatus!=2 ";
        }

        _strSql += " and  sr.projectid=:projectid " +
                " order by sr.createtime asc ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectStage> _stageList = getEntitys(_strSql, _params, CrmProjectStage.class);
        return _stageList;


    }

    public List<CrmProjectStage2> getProjectStageList2(String projectid, String forType) {

        String _strSql =
                " select sr.recid, sr.stageid,s.recname,sr.recorder,s.datastageid,s.stagetype,sr.stagestatus " +
                        " from crm_project_stage s " +
                        " inner join crm_project_stage_relate sr on s.recid=sr.stageid " +
                        " where sr.recstatus=1  " +
                        " and s.recstatus=1 ";

        //过滤掉已经完成的阶段
        if (forType == "task") {
            _strSql += " and  sr.stagestatus!=2 ";
        }

        _strSql += " and  sr.projectid=:projectid " +
                " order by sr.createtime asc ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProjectStage2> _stageList = getEntitys(_strSql, _params, CrmProjectStage2.class);
        return _stageList;


    }


    public List<CrmProject> getProject(String projectid) {
        String _strSql = " select recid,recname,current_stage,projecttype,projectstatus,completedtime  from crm_project where recid=:projectid";
        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        List<CrmProject> _projectList = getEntitys(_strSql, _params, CrmProject.class);
        return _projectList;
    }

    public int insertProject(String projectid, String projectName, int projectType, int userId) {

        int _result = 0;
        String _strSql = " insert into crm_project(recid,recname,projecttype,reccreator) "
                + " values(:recid,:recname,:projecttype,:reccreator) ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", projectid);
        _params.put("recname", projectName);
        _params.put("projecttype", projectType);
        _params.put("reccreator", userId);
        _result = updateEntity(_strSql, _params);
        return _result;

    }

    public List<CrmProjectFolder> getProjectFoldersById(String projectid) {

        String _strSql = " select recid,recname,stageid,foldertype,relatedid,reccreator,prefixname,innerfoldertype,islawyerfolder  " +
                " from crm_project_folder " +
                " where recstatus=1 " +
                " and projectid=:projectid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        return getEntitys(_strSql, _params, CrmProjectFolder.class);
    }

    public int updateProjectMember(ProjectMember _member, int userid) {
        int _result = 0;
        String _strSql = "  update crm_project_member set ismanager=:ismanager,ishost=:ishost where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", _member.getRecid());
        _params.put("ismanager", _member.getIsmanager());
        _params.put("ishost", _member.getIshost());
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    public int updateProjectMemberBatch(List<ProjectMember> members, int userid) {

        int _result = 0;
        int _finalResult = 0;
        for (ProjectMember _member : members) {
            _result = updateProjectMember(_member, userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public List<CrmProject> getProjectList(int userid) {

        String _strSql = " select recid,recname,current_stage,projecttype,projectstatus " +
                "  from crm_project" +
                " where recstatus=1 " +
                " and recid in (select projectid from crm_project_member where recstatus=1 and userid=:userid) order by createtime desc";

        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);
        List<CrmProject> _list = getEntitys(_strSql, _params, CrmProject.class);
        return _list;
    }

    public List<CrmProject> getProjectList(ProjectGetListRequest _request, int userid) {
        String searchkey = _request.getSearchkey();

        String _strSql = " select recid,recname,current_stage,projecttype,projectstatus,completedtime " +
                "  from crm_project" +
                " where recstatus=1 " +
                " and recid in (select projectid from crm_project_member where recstatus=1 and userid=:userid) ";

        String _where_name_sql = " and recname like" + "'%" + searchkey + "%'";
        String _orderby_sql = " order by createtime desc  ";

        if (!searchkey.isEmpty()) {
            _strSql += _where_name_sql;
        }
        _strSql += _orderby_sql;

        if (_request.getPageindex() > 0) {
            int _pageindex = _request.getPageindex();
            int _pageSize = _request.getPagesize();
            int _offset = (_pageindex - 1) * _pageSize;
            _strSql += " limit " + _pageSize + " offset " + _offset;
        }

        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);
        List<CrmProject> _list = getEntitys(_strSql, _params, CrmProject.class);
        return _list;
    }


    @Transactional
    public ProjectSaveStageResponse saveProjectStage(ProjectStageSaveRequest _request, int userid) {

        ProjectSaveStageResponse _response = new ProjectSaveStageResponse();
        int projectType = _request.getProjecttype();
        String stageName = _request.getStagename();
        EntityManager _entityManager = getEntityManager();


        //check if name exists
        String _strSql = " select count(1) from crm_project_stage " +
                " where recstatus=1 " +
                " and  projecttype=:projecttype" +
                " and recname=:recname";
        javax.persistence.Query _query = _entityManager.createNativeQuery(_strSql);
        _query.setParameter("projecttype", projectType);
        _query.setParameter("recname", stageName);
        List<BigInteger> resultList = _query.getResultList();


        BigInteger _tmpResult = resultList.get(0);
        int _recorder = _tmpResult.intValue();
        //相同名字的阶段已经存在
        if (_recorder > 0) {
            //_response.result = -1;
            //  return _response;
        }

        //get max order
        _strSql = "select max(recorder) from crm_project_stage where projecttype=:projecttype";
        javax.persistence.Query _query2 = _entityManager.createNativeQuery(_strSql);
        _query2.setParameter("projecttype", projectType);
        List<Integer> resultList2 = _query2.getResultList();
        _recorder = resultList2.get(0);
        int _newOrder = _recorder + 1;


        //get max recid
        _strSql = "select max(recid) from crm_project_stage ";
        javax.persistence.Query _query4 = _entityManager.createNativeQuery(_strSql);
        List<Integer> resultList4 = _query4.getResultList();
        int _recid = resultList4.get(0);
        int _newRecid = _recid + 1;


        //insert project stage
        _strSql = " insert into crm_project_stage(recid,projecttype,recname,stagetype,datastageid,recorder) " +
                " values(:recid,:projecttype,:recname,:stagetype,:datastageid,:recorder) ";
        javax.persistence.Query _query3 = _entityManager.createNativeQuery(_strSql);
        _query3.setParameter("recid", _newRecid);
        _query3.setParameter("projecttype", projectType);
        _query3.setParameter("recname", stageName);
        //自定义阶段
        _query3.setParameter("stagetype", 1);
        _query3.setParameter("datastageid", 0);
        _query3.setParameter("recorder", _newOrder);
        int _result = _query3.executeUpdate();

        _response.setOrder(_newOrder);
        _response.setStageid(_newRecid);
        _response.setResult(_result);

        return _response;
    }

    private ProjectCause toProjectCause(CrmProjectCause cause) {
        ProjectCause _cause = new ProjectCause();
        _cause.setRecid(cause.getRecid());
        _cause.setRecname(cause.getRecname());
        _cause.setParentid(cause.getParentid());
        if (cause.getChildcount() > 0) {
            _cause.setHaschild(true);
        } else {

            _cause.setHaschild(false);
        }
        return _cause;
    }

    //获取任务成员
    private List<CrmTaskMember> getTaskMember(String taskid) {

        String _strSql = " select m.recid,m.groupid,m.userid,m.roleid,m.ismanager,m.ishost,coalesce(u.realname,'') as username,m.reccreator,m.recorder " +
                "  from  crm_task_member m" +
                " inner join crm_user u on m.userid=u.id " +
                " where m.recstatus=1 " +
                " and  taskid=:taskid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("taskid", taskid);
        List<CrmTaskMember> _results = getEntitys(_strSql, _params, CrmTaskMember.class);
        return _results;

    }


    //获取创建文件夹的模板文件夹名称
    public List<CrmPorjectFolderSpecial> getProjectFolderSpecial(int projectType, int stageid) {

        List<CrmProjectStage> _stages = getProjectStage(stageid);
        if (_stages != null && _stages.size() > 0) {
            if (_stages.get(0).getStagetype() == BaseEnum.StageType.Define.getStageType()) {
                //使用用户自定义阶段id

                if (projectType == CommonConstant.ProjectTypePeople) {
                    stageid = CommonConstant.userDefineStagePeople;
                } else if (projectType == CommonConstant.ProjectTypeLaw) {
                    stageid = CommonConstant.userDefineStageLaw;
                } else {

                    // do nothing
                }

            }
        }
        String _strSql = " select recid,projecttype,stageid,showname " +
                " from crm_project_folder_special " +
                " where recstatus=1 " +
                " and projecttype=:projecttype and stageid=:stageid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projecttype", projectType);
        _params.put("stageid", stageid);
        List<CrmPorjectFolderSpecial> _list = getEntitys(_strSql, _params, CrmPorjectFolderSpecial.class);
        return _list;
    }


    //如果是新增项目的时候调用，没有projectdi,就在保存项目的过程中新增文件夹
    //如果是编辑项目的时候调用，就直接新建一个文件夹
    @Transactional
    public ProjectSaveFolderResponse saveProjectDefineFolder(ProjectSaveFolderRequest _request, int userid) {

        int _result = 0;
        String _projectid = _request.getProjectid();
        String _folderName = _request.getFoldername();
        String _folderid = UUID.randomUUID().toString();
        int _stageid = _request.getStageid();
        boolean _isclientfolder = _request.getIsclientfolder();

        if (!_projectid.isEmpty()) {

            String _strSql = " insert into crm_project_folder(recid,recname,projectid,stageid," +
                    "reccreator,foldertype,relatedid,prefixname,innerfoldertype,islawyerfolder) " +
                    "  values(:recid,:recname,:projectid,:stageid,:reccreator,:foldertype,:relatedid," +
                    ":prefixname,:innerfoldertype,:islawyerfolder) ";


            String _getNextInnerFolderTypeSql =
                    " select (coalesce(max(innerfoldertype),0)+1) as nextInnerfoldertype " +
                            " from crm_project_folder " +
                            " where projectid=:projectid " +
                            " and foldertype=4 ";


            String _strGetFolder = " select count(1) " +
                    " from crm_project_folder " +
                    " where projectid=:projectid " +
                    " and stageid=:stageid " +
                    " and foldertype=4  " +
                    " and  recname=:recname ";

            Map<String, Object> _params = new HashMap<>();
            _params.put("projectid", _projectid);
            _params.put("stageid", _stageid);
            _params.put("recname", _folderName);
            int _theFolderCount = getEntityCount(_strGetFolder, _params);
            if (_theFolderCount > 0) {
                ProjectSaveFolderResponse _response = new ProjectSaveFolderResponse();
                _response.setFolderid("");
                _response.setFoldername("");
                return _response;
            }


            int _innerFolerType = 0;
            _params.clear();
            _params.put("projectid", _projectid);
            _innerFolerType = getMax(_getNextInnerFolderTypeSql, _params);
            boolean _isdefinefolder = !_request.getIsclientfolder();
            try {

                _params.clear();
                _params.put("recid", _folderid);
                _params.put("recname", _folderName);
                _params.put("projectid", _projectid);
                _params.put("stageid", _stageid);
                _params.put("reccreator", userid);
                _params.put("foldertype", BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType());
                _params.put("relatedid", _request.getClientid());
                _params.put("prefixname", "");
                _params.put("innerfoldertype", _innerFolerType);
                _params.put("islawyerfolder", !_isclientfolder);
                //_params.put("isdefinefolder", _isdefinefolder);
                _result = updateEntity(_strSql, _params);

                //发送群消息
                if (_result > 0) {

                    CrmUser _userInfo = _commonRepository.getUserInfo(userid);
                    String _userName = "";
                    if (_userInfo != null) {
                        _userName = _userInfo.getRealname();
                    }
                    String _content = String.format("%s创建了自定义文件夹：%s", _userName, _folderName);
                    SendIMGroupMessage(_projectid, _stageid, _content, _isclientfolder, userid);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                throw ex;
            }
        }

        ProjectSaveFolderResponse _response = new ProjectSaveFolderResponse();
        _response.setFolderid(_folderid);
        _response.setFoldername(_folderName);
        _response.setFoldertype(BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType());

        return _response;

    }


    //返回所有项目下阶段的文件夹
    public List<GetAllProjectFolderResponse> getAllPorjectFolders(ProjectGetAllFolderRequest request, int userid) {
        List<GetAllProjectFolderResponse> _results = new ArrayList<>();

        //projects
        List<CrmProject> _projects = getProjectList(userid);
        for (CrmProject p : _projects) {
            String _projectid = p.getRecid();
            if (_projectid.equals(request.getProjectid())) {
                continue;
            }

            String _projectName = p.getRecname();
            GetAllProjectFolderResponse _projectResponse = new GetAllProjectFolderResponse();

            //members
            List<CrmProjectMember> _members = getProjectMember(_projectid, userid);

            //folders
            List<CrmProjectFolder> _folders = getProjectFolder(_projectid, userid);

            //stages
            List<CrmProjectStage> _stages = getProjectStageList(_projectid);
            List<ProjectFolderStageRequest> _stagesResponse = new ArrayList<>();
            for (CrmProjectStage s : _stages) {
                int _stageid = s.getStageid();
                String _stageName = s.getStagename();

                ProjectFolderStageRequest _stage = new ProjectFolderStageRequest();
                _stage.setStageid(_stageid);
                _stage.setStagename(_stageName);

                //如果是律师协作团队成员，可以看全部文件夹
                List<CrmProjectMember> _stageMembers = _members.stream().filter(x -> x.getStageid() == _stageid && x.getUserid() == userid).collect(Collectors.toList());
                long _memberCount = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()).count();

                List<CrmProjectFolder> _stageFolders = _folders.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                List<CrmProjectFolder> _commonFolders = _folders.stream().filter(x -> x.getStageid() == 0).collect(Collectors.toList());

                List<ProjectFolderRequest> _foldersResponse = new ArrayList<>();

                // project folder
                for (CrmProjectFolder f : _commonFolders) {
                    ProjectFolderRequest _folder = new ProjectFolderRequest();
                    _folder.setFoldername(f.getPrefixname() + f.getRecname());
                    _folder.setFolderid(f.getRecid());
                    _foldersResponse.add(_folder);
                }

                if (_memberCount > 0) {
                    for (CrmProjectFolder f : _stageFolders) {
                        ProjectFolderRequest _folder = new ProjectFolderRequest();
                        _folder.setFoldername(f.getPrefixname() + f.getRecname());
                        _folder.setFolderid(f.getRecid());

                        if (f.islawyerfolder()) {
                            _folder.setIslawyerfolder(true);
                        } else {
                            _folder.setIslawyerfolder(false);
                        }

                        _foldersResponse.add(_folder);


                    }
                } else {
                    for (CrmProjectFolder f : _stageFolders) {
                        if (!f.islawyerfolder()) {
                            ProjectFolderRequest _folder = new ProjectFolderRequest();
                            _folder.setFoldername(f.getPrefixname() + f.getRecname());
                            _folder.setFolderid(f.getRecid());
                            _foldersResponse.add(_folder);
                        }
                    }
                }


                if (_foldersResponse != null && _foldersResponse.size() > 0) {
                    _stage.setFolders(_foldersResponse);
                }

                if (_stageMembers.size() > 0) {
                    _stagesResponse.add(_stage);
                }

            }
            if (_stagesResponse != null && _stagesResponse.size() > 0) {
                _projectResponse.setStages(_stagesResponse);
                _projectResponse.setProjectid(_projectid);
                _projectResponse.setProjectname(_projectName);
            }

            if (_projectResponse != null && _projectResponse.getStages() != null && _projectResponse.getStages().size() > 0) {
                _results.add(_projectResponse);
            }
        }
        return _results;
    }


    public int updateProjectFile(ProjectFile file) {
        int _result = 0;
        String _strSql = "  update crm_project_file set filename=:filename where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", file.getFileid());
        _params.put("filename", file.getFilename());
        _result = updateEntity(_strSql, _params);
        return _result;
    }


    public List<CrmProjectStage> getStages(List<String> projectids, int userid) {

        String _strSql = " select sr.recid, sr.projectid, sr.stageid, sr.recstatus, sr.recorder, sr.reccreator, " +
                "sr.createtime, sr.stagestatus, sr.completedtime,false as iscomplete  " +
                " from crm_project_stage_relate  sr " +
                " inner join crm_project p on sr.projectid=p.recid  " +
                " where p.recstatus=1 " +
                " and sr.recstatus=1 " +
                " and sr.projectid in (:projectids) ";

        String _ids = String.join(",", projectids);

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectids", projectids);
        List<CrmProjectStage> _list = getEntitys(_strSql, _params, CrmProjectStage.class);

        return _list;
    }


    public List<CrmProjectFolder> getProjectFolders(List<String> projectids, int userid) {

        String _strSql = " select recid,recname,stageid,foldertype,relatedid,reccreator,prefixname,innerfoldertype,islawyerfolder " +
                " from crm_project_folder " +
                " where recstatus=1 " +
                " and projectid in (:projectids) ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectids", projectids);
        List<CrmProjectFolder> _list = getEntitys(_strSql, _params, CrmProjectFolder.class);
        return _list;
    }

    @Transactional
    public int projecFileMerge(ProjectFileMergeRequest _request, int userid) {
        int _result = 0;
        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        String _folderid = _request.getFolderid();

        List<CrmProject> _projects = getProject(_projectid);
        List<CrmProjectStage> _stages = getProjectStage(_stageid);
        String _projectName = "";
        String _stageName = "";

        if (_projects != null && _projects.size() > 0) {
            _projectName = _projects.get(0).getRecname();
        }

        if (_stages != null && _stages.size() > 0) {
            _stageName = _stages.get(0).getStagename();
        }


        boolean _isLawyerFolder = false;
        List<CrmProjectFolder> _folders = getProjectFolderById(_folderid);
        if (_folders != null && _folders.size() > 0) {
            CrmProjectFolder _theFolder = _folders.get(0);
            _isLawyerFolder = _theFolder.islawyerfolder();
        }


        String _messageTemplate = "%s已经复制文件：%s到项目%s的%s阶段";
        _messageTemplate = "用户姓名已经复制文件：文件名到本阶段资料下的文件夹：文件夹名称";
        _messageTemplate = "%s已经复制文件：%s到本阶段资料下的文件夹：%s";

        String _theUserName = "";
        CrmUser _theUser = _commonRepository.getUserInfo(userid);
        if (_theUser != null) {
            _theUserName = _theUser.getRealname();
        }

        String _theFolderName = "";
        List<CrmProjectFolder> _theFolders = getProjectFolderById(_folderid);
        if (_theFolders != null && _theFolders.size() > 0) {
            CrmProjectFolder _theFolder = _theFolders.get(0);
            _theFolderName = _theFolder.getPrefixname() + _theFolder.getRecname();
        }

        List<ProjectFile> _files = _request.getFiles();
        for (ProjectFile f : _files) {
            f.setFolderid(_folderid);
            _result = insertProjectFile(_projectid, _stageid, _files, userid);

            //send copy system message\
            List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
            if (_isLawyerFolder) {
                List<CrmChatGroupPart> _lawyerChatGroups = _chatGroups.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).collect(Collectors.toList());
                List<String> _chatGroupIds = _lawyerChatGroups.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                String _message = String.format(_messageTemplate, _theUserName, f.getFilename(), _theFolderName);
                sendIMMessage(_chatGroupIds, _message, userid, 1);
            } else {
                List<String> _chatGroupIds = _chatGroups.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                String _message = String.format(_messageTemplate, _theUserName, f.getFilename(), _theFolderName);
                sendIMMessage(_chatGroupIds, _message, userid, 1);
            }
        }
        return _result;
    }

    public int getNextInnerFolderType(String projectid) {

        String _getMaxInnerFolerType = " select (coalesce(max(innerfoldertype),0)+1) as nextInnerfoldertype " +
                " from crm_project_folder " +
                " where projectid=:projectid " +
                " and foldertype=4 ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectid", projectid);
        return getMax(_getMaxInnerFolerType, _params);
    }

    @Transactional
    public int projectStatusChangeSimple(ProjectCompleteRequest _request, int projectStatus, int userid) {

        String _projectid = _request.getProjectid();
        Map<String, Object> _params = new HashMap<>();

        if (projectStatus == 1) {
            //标记项目所有阶段为完成
            List<CrmProjectStageRelate> _stageRelates = getProjectStageRelate(_projectid);
            for (CrmProjectStageRelate r : _stageRelates) {
                String _strSql = " update crm_project_stage_relate set stagestatus=:stagestatus, completedtime=now() " +
                        " where recid=:recid ";
                _params.clear();
                _params.put("recid", r.getRecid());

                String _whereSql = "";
                if (projectStatus == 1) {
                    _strSql += _whereSql = " and stagestatus=1 ";
                    _params.put("stagestatus", BaseEnum.StageStatus.Complete.getStageStatus());
                } else {
                    _params.put("stagestatus", BaseEnum.StageStatus.Start.getStageStatus());
                }
                updateEntity(_strSql, _params);
            }

            //标记所有的任务为完成
            // taskstatus int default 1 comment '任务状态：暂停:0,正常:1,完成:2',
            //projectstatus int default 0 comment '0：未完成，1 已经完成',
            int _taskStatus = 0;
            if (projectStatus == 1) {
                _taskStatus = 2;
            } else {
                _taskStatus = 1;
            }

            String _completeTaskSql = " update crm_task set taskstatus=:taskstatus,completetime=now() " +
                    "where recid=:recid ";
            List<CrmProjectTask> _tasks = getProjectTask(_projectid);
            for (CrmProjectTask t : _tasks) {
                _params.clear();
                _params.put("taskstatus", _taskStatus);
                _params.put("recid", t.getTaskid());
                updateEntity(_completeTaskSql, _params);
            }
        }
        //标记项目为已完成
        String _strSql = " update crm_project set projectstatus=:projectstatus, completedtime=now() where recid=:recid   ";
        _params.clear();
        _params.put("recid", _request.getProjectid());
        _params.put("projectstatus", projectStatus);
        int _result = updateEntity(_strSql, _params);

        return _result;
    }

    @Transactional
    public int deleteProject(ProjectCompleteRequest _request, int userid) {

        String _projectId = _request.getProjectid();
        String _strSql = " update crm_project set recstatus=0 where recid=:recid   ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", _projectId);

        //delete chat group
        List<CrmChatGroupPart> _groups = getProjectChatGroup(_projectId);
        deleteProjectChatGroupBatch(_groups, userid);


        //delete project task
        List<CrmProjectTask> _tasks = getProjectTask(_projectId);
        for (CrmProjectTask t : _tasks) {
            deleteProjectTask(t.getTaskid());
        }

        return updateEntity(_strSql, _params);
    }


    public void SendIMGroupMessage_fix(String projectid, String content, int userid, JSONObject custExtJsonObject) {
        List<CrmChatGroupPart> _groups = getProjectChatGroup(projectid);
        if (_groups != null && _groups.size() > 0) {
            for (CrmChatGroupPart c : _groups) {
                String _groupid = c.getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(c);
                logger.info("{}分组id，发送内容{},发送人{}", _groupid, _content, userid);
                //
                _imService.sendMessage(0, c.getGroupname(), _groupid, _title, _content, "text", "", null, custExtJsonObject, userid);
            }
        }
    }


    public void SendIMGroupMessage(String projectid, String content, int userid) {

        List<CrmChatGroupPart> _groups = getProjectChatGroup(projectid);
        if (_groups != null && _groups.size() > 0) {
            JSONObject obj = new JSONObject();
            JSONObject data = new JSONObject();
            obj.put("type", "system");

            data.put("type", BaseEnum.ChatType.Project.getChatType());
            data.put("projectid", projectid);
            obj.put("data", data);

            Optional<CrmChatGroupPart> _theGroup = _groups.stream().filter(x -> x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();

            Optional<CrmChatGroupPart> _theLawyerGroup = _groups.stream().filter(x -> x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();

            if (_theGroup.isPresent()) {
                String _groupid = _theGroup.get().getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(_theGroup.get());
                _imService.sendMessage(0, _theGroup.get().getGroupname(), _groupid, _title, _content, "text", "", null, obj, userid);
            }

            if (_theLawyerGroup.isPresent()) {
                String _groupid = _theLawyerGroup.get().getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(_theLawyerGroup.get());
                _imService.sendMessage(0, _theLawyerGroup.get().getGroupname(), _groupid, _title, _content, "text", "", null, obj, userid);
            }
        }
    }

    public void SendIMGroupMessage(String projectid, int stageid, String content, int userid, JSONObject custExtJsonObject) {

        List<CrmChatGroupPart> _groups = getProjectChatGroup(projectid);
        if (_groups != null && _groups.size() > 0) {

            Optional<CrmChatGroupPart> _theGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();


            Optional<CrmChatGroupPart> _theLawyerGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();


            if (_theGroup.isPresent()) {
                String _groupid = _theGroup.get().getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(_theGroup.get());
                _imService.sendMessage(0, _theGroup.get().getGroupname(), _groupid, _title, _content, "text", "", null, custExtJsonObject, userid);
            }

            if (_theLawyerGroup.isPresent()) {
                String _groupid = _theLawyerGroup.get().getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(_theLawyerGroup.get());
                _imService.sendMessage(0, _theLawyerGroup.get().getGroupname(), _groupid, _title, _content, "text", "", null, custExtJsonObject, userid);
            }
        }
    }


    public void SendIMGroupMessage(String projectid, int stageid, String content, boolean isClientFolder, int userid) {

        List<CrmChatGroupPart> _groups = getProjectChatGroup(projectid);
        if (_groups != null && _groups.size() > 0) {
            JSONObject obj = new JSONObject();
            JSONObject data = new JSONObject();
            obj.put("type", "system");

            data.put("type", BaseEnum.ChatType.Project.getChatType());
            data.put("projectid", projectid);
            obj.put("data", data);

            Optional<CrmChatGroupPart> _theGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();


            Optional<CrmChatGroupPart> _theLawyerGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();


            if (isClientFolder) {
                if (_theGroup.isPresent()) {
                    String _groupid = _theGroup.get().getGroupid();
                    SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                    String _strNow = _dataFormat.format(new Date());
                    String _content = String.format("%s", content);
                    String _title = getMsgTitle(_theGroup.get());
                    _imService.sendMessage(1, _theGroup.get().getGroupname(), _groupid, _title, _content, "text", "", null, obj, userid);
                }
            }

            if (_theLawyerGroup.isPresent()) {
                String _groupid = _theLawyerGroup.get().getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(_theLawyerGroup.get());
                _imService.sendMessage(1, _theLawyerGroup.get().getGroupname(), _groupid, _title, _content, "text", "", null, obj, userid);
            }
        }
    }

    public void SendIMGroupMessageFile(String projectid, int stageid, String content, boolean isClientFolder, String extData, JSONObject extJsonObject, int userid) {
        List<CrmChatGroupPart> _groups = getProjectChatGroup(projectid);
        if (_groups != null && _groups.size() > 0) {

            Optional<CrmChatGroupPart> _theGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();


            Optional<CrmChatGroupPart> _theLawyerGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();


            if (isClientFolder) {
                if (_theGroup.isPresent()) {
                    String _groupid = _theGroup.get().getGroupid();
                    SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                    String _strNow = _dataFormat.format(new Date());
                    String _content = String.format("%s", content);
                    String _title = getMsgTitle(_theGroup.get());
                    _imService.sendMessage(1, _theGroup.get().getGroupname(), _groupid, _title, _content, "file", extData, extJsonObject, userid);
                }
            }

            if (_theLawyerGroup.isPresent()) {
                String _groupid = _theLawyerGroup.get().getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(_theLawyerGroup.get());
                _imService.sendMessage(1, _theLawyerGroup.get().getGroupname(), _groupid, _title, _content, "file", extData, extJsonObject, userid);
            }
        }
    }
    public void SendIMGroupMessageFile2(String projectid, int stageid, String content, boolean isClientFolder, String extData, JSONObject extJsonObject, int userid) {
        List<CrmChatGroupPart> _groups = getProjectChatGroup(projectid);
        if (_groups != null && _groups.size() > 0) {

            Optional<CrmChatGroupPart> _theGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();


            Optional<CrmChatGroupPart> _theLawyerGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();


            if (isClientFolder) {
                if (_theGroup.isPresent()) {
                    String _groupid = _theGroup.get().getGroupid();
                    SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                    String _strNow = _dataFormat.format(new Date());
                    String _content = String.format("%s", content);
                    String _title = getMsgTitle(_theGroup.get());
                    _imService.sendMessage2(1, _theGroup.get().getGroupname(), _groupid, _title, _content, "file", extData, extJsonObject, userid);
                }
            }

            if (_theLawyerGroup.isPresent()) {
                String _groupid = _theLawyerGroup.get().getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(_theLawyerGroup.get());
                _imService.sendMessage2(1, _theLawyerGroup.get().getGroupname(), _groupid, _title, _content, "file", extData, extJsonObject, userid);
            }
        }
    }
  /**
    public void SendIMGroupMessageFile(String projectid, int stageid, String content, boolean isClientFolder, String extData, int userid) {

        List<CrmChatGroupPart> _groups = getProjectChatGroup(projectid);
        if (_groups != null && _groups.size() > 0) {

            Optional<CrmChatGroupPart> _theGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();


            Optional<CrmChatGroupPart> _theLawyerGroup = _groups.stream().filter(x -> x.getStageid() == stageid
                    && x.getChattype() == BaseEnum.ChatType.Project.getChatType()
                    && x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();


            if (isClientFolder) {
                if (_theGroup.isPresent()) {
                    String _groupid = _theGroup.get().getGroupid();
                    SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                    String _strNow = _dataFormat.format(new Date());
                    String _content = String.format("%s", content);
                    String _title = getMsgTitle(_theGroup.get());
                    _imService.sendMessage(1, _theGroup.get().getGroupname(), _groupid, _title, _content, "file", extData, userid);
                }
            }

            if (_theLawyerGroup.isPresent()) {
                String _groupid = _theLawyerGroup.get().getGroupid();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                String _strNow = _dataFormat.format(new Date());
                String _content = String.format("%s", content);
                String _title = getMsgTitle(_theLawyerGroup.get());
                _imService.sendMessage(1, _theLawyerGroup.get().getGroupname(), _groupid, _title, _content, "file", extData, userid);
            }
        }
    }
   **/

    private List<CrmProjectMain> getProjectMain(String projectid) {

        int _result = 0;
        String _strSql = " select recid, recname from  crm_project where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", projectid);
        return getEntitys(_strSql, _params, CrmProjectMain.class);
    }

    private String getMsgTitle(CrmChatGroupPart group) {
        String _title = "律协";
        if (group.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType())
            _title = "委协";
        _title = String.format("%s-%s", _title, group.getTopicname());

        return _title;
    }

    public String checkNull(String _theValue) {

        if (_theValue == null) {
            return "";
        } else {
            return _theValue;
        }
    }


    public void sendIMMessage(List<String> groupids, String content, int userid, int pushFlag) {
        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        if (groupids != null && groupids.size() > 0) {
            for (String _groupid : groupids) {
                if (!_groupid.isEmpty()) {
                    String _strNow = _dataFormat.format(new Date());
                    //String _content = String.format("%s，%s", _strNow, content);
                    String _content = String.format("%s", content);

                    List<CrmChatGroupPart> _groups = getChatGroupByGroupId(_groupid);
                    String _title = getMsgTitle(_groups.get(0));

                    _imService.sendMessage(pushFlag, _groups.get(0).getGroupname(), _groupid, _title, _content, "text", "", userid);
                }
            }
        }
    }


    @Transactional
    public int saveProjectName(ProjectSaveNameRequest _request, int userid) throws Exception {

        int _result = 0;
        String _projectid = _request.getProjectid();
        String _newProjectName = _request.getProjectname();

        String _strSql = " update crm_project set recname=:recname where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", _projectid);
        _params.put("recname", _newProjectName);
        _result = updateEntity(_strSql, _params);

        List<CrmProject> _theProjects = getProject(_projectid);
        if (_theProjects != null && _theProjects.size() > 0) {
            CrmProject _project = _theProjects.get(0);
            if (_project.getRecname().equals(_newProjectName)) {

                List<CrmChatGroupPart> _groups = getProjectChatGroup(_projectid);
                if (_groups != null && _groups.size() > 0) {

                    for (CrmChatGroupPart g : _groups) {

                        String _groupId = g.getGroupid();
                        int _theStageId = g.getStageid();

                        List<CrmProjectStage> _stages = getProjectStage(_theStageId);
                        String _theStageName = "";
                        if (_stages != null && _stages.size() > 0) {
                            _theStageName = _stages.get(0).getStagename();
                        }

                        String _intruductionSubName = "委协";
                        String _groupSubName = "委托";
                        if (g.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()) {
                            _groupSubName = "律师";
                            _intruductionSubName = "律协";
                        }

                        String _finalGroupName = "[" + _theStageName + "]" + _newProjectName + "_" + _groupSubName;
                        _finalGroupName = _intruductionSubName + "-" + _newProjectName;

                        if (_finalGroupName.length() > 10) {
                            _finalGroupName = _finalGroupName.substring(0, 10);
                        }

                        String _imGroupName = _intruductionSubName + "-" + _newProjectName;
                        if (_imGroupName.length() > 10) {
                            _imGroupName = _imGroupName.substring(0, 10);
                        }


                        String _instrduction = _intruductionSubName + "-" + _newProjectName;
                        if (_instrduction.length() > 100) {
                            _instrduction = _instrduction.substring(0, 100);
                        }

                        _imService.updataeIMGroup(_groupId, _finalGroupName, _instrduction, userid);
                    }

                }
            }
        }

        if (_result > 0) {
            new Thread(() -> {

                //send system message
                CrmUser _theUser = _commonRepository.getUserInfo(userid);
                String _content = String.format("%s编辑了项目名称", _theUser.getRealname());

                List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
                List<String> _messageGroupIds = _chatGroups.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                if (!_content.isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                    sendIMMessage(_messageGroupIds, _content, userid, 0);
                }
            }).start();
        }

        return _result;


    }


    private String getFieldDisplayName(List<CrmProjectInfoField> _fieldsInfos, String fieldName) {
        String _fieldShowName = "";

        Optional<CrmProjectInfoField> _fieldInfo = _fieldsInfos.stream().filter(x -> x.getFieldname().equals(fieldName)).findFirst();
        if (_fieldInfo.isPresent()) {
            _fieldShowName = _fieldInfo.get().getDisplayname();
        }

        return _fieldShowName;

    }

    @Transactional
    public int saveProjectInfo(ProjectSaveInfoRequest _request, int userId) throws Exception {
        int _result = 0;


        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        int _clientPersonType = BaseEnum.PersonType.Client.getPersonType();
        int _litigantPersonType = BaseEnum.PersonType.litigant.getPersonType();


        List<CrmProject> _projects = getProject(_projectid);
        int _projectType = _projects.get(0).getProjecttype();


        List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);
        List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
        String _currentStageName = _currentSageNameList.get(0).getStagename();
        String _folderStageName = "(" + _currentStageName + ")";
        _folderStageName = "";


        ProjectInfoFieldGetRequest re = new ProjectInfoFieldGetRequest();
        re.setProjecttype(_projectType);
        re.setStageid(_stageid);
        List<CrmProjectInfoField> _fieldsInfos = getProjectInfoFields(re, _stageid);

        List<CrmProjectClient> _savedProjectClient = getProjectClient(_projectid);
        List<CrmProjectClient> _savedStageProjectClient =
                _savedProjectClient.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());

        //当前阶段的对方委托人
        List<CrmProjectClient> _clients =
                _savedStageProjectClient.stream().filter(x -> x.getPersontype() == _clientPersonType)
                        .collect(Collectors.toList());

        //当前阶段对方当事人
        List<CrmProjectClient> _litigants =
                _savedStageProjectClient.stream().filter(x -> x.getPersontype() == _litigantPersonType)
                        .collect(Collectors.toList());
        ProjectInfo _requestProjectInfo = _request.getInfo();
        List<ProjectClient> _requestClients = _requestProjectInfo.getClient();
        List<ProjectClient> _requestLitigants = _requestProjectInfo.getLitigant();

        //委托人只有一个，所以只需要更新即可
        //更新委托人文件夹
        List<CrmProjectFolder> _folders = getProjectFolder(_projectid, userId);
        //todo:更新文件夹，更新聊天组数据
        if (_requestClients != null) {
            updateProjectClient(_requestClients);
            ProjectClient _theClient = _requestClients.get(0);
            String _clientId = _theClient.getRecid();
            String _clientName = _theClient.getName();


            if (_folders != null) {
                List<CrmProjectFolder> _stageFolders = _folders.stream().filter(x -> x.getStageid() == _stageid
                        && x.getRelatedid() != null && x.getRelatedid().equals(_clientId)).collect(Collectors.toList());
                for (CrmProjectFolder f : _stageFolders) {
                    updateProjectFolderName(f.getRecid(), _clientName);
                }
            }
        }

        //更新对方当事人
        List<CrmProjectBasicFolder> _basicFolder = getProjectBasicFolder(_projectType);
        int _ligigantStageFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();
        List<CrmProjectBasicFolder> _ligigantStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _ligigantStageFolderType).collect(Collectors.toList());

        //get special folder
        String _newFolderName = "";
        List<CrmPorjectFolderSpecial> _folderSpecials = getProjectFolderSpecial(_projectType, _stageid);
        if (_folderSpecials != null && _folderSpecials.size() > 0) {
            CrmPorjectFolderSpecial _special = _folderSpecials.get(0);
            _newFolderName = _special.getShowname();
        }

        if (_requestLitigants != null) {
            if (_litigants != null && _litigants.size() > 0) {
                for (ProjectClient _litigant : _requestLitigants) {
                    if (_litigant.getRecid() == null || _litigant.getRecid().isEmpty()) {
                        String _clientRecid = UUID.randomUUID().toString();
                        insertProjectClientSingle(_projectid, _stageid, _litigantPersonType, _clientRecid, _litigant);

                        //添加对方当事人文件夹
                        String _realFolderName = "";
                        for (CrmProjectBasicFolder _folder : _ligigantStageFolders) {

                            String _theStagePartFolderName = "";
                            if (_folder.getIsReplaceable() && !_newFolderName.isEmpty()) {
                                _theStagePartFolderName = "正式提交给" + _newFolderName + "的材料";
                                _realFolderName = _folderStageName + _theStagePartFolderName;
                            } else {
                                _realFolderName = _folderStageName + _folder.getRecname();
                            }

                            int _innerFolderType = _folder.getInnerfoldertype();
                            boolean _isLawyerFolder = false;
                            String _theFolderRecid = UUID.randomUUID().toString();
                            insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _realFolderName, _ligigantStageFolderType, _clientRecid, _litigant.getName(), _innerFolderType, _isLawyerFolder, userId);
                        }

                    } else {
                        long _theLitigantCount = _litigants.stream().filter(x -> x.getRecid() != null
                                && x.getRecid().equals(_litigant.getRecid())).count();
                        if (_theLitigantCount == 0) {
                            String _clientRecid = UUID.randomUUID().toString();
                            insertProjectClientSingle(_projectid, _stageid, _litigantPersonType, _clientRecid, _litigant);

                            //添加对方当事人文件夹
                            String _realFolderName = "";
                            for (CrmProjectBasicFolder _folder : _ligigantStageFolders) {

                                String _theStagePartFolderName = "";
                                if (_folder.getIsReplaceable() && !_newFolderName.isEmpty()) {
                                    _theStagePartFolderName = "正式提交给" + _newFolderName + "的材料";
                                    _realFolderName = _folderStageName + _theStagePartFolderName;
                                } else {
                                    _realFolderName = _folderStageName + _folder.getRecname();
                                }

                                int _innerFolderType = _folder.getInnerfoldertype();
                                boolean _isLawyerFolder = false;
                                String _theFolderRecid = UUID.randomUUID().toString();
                                insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _realFolderName, _ligigantStageFolderType, _clientRecid, _litigant.getName(), _innerFolderType, _isLawyerFolder, userId);
                            }

                        } else {
                            updateProjectClientSingle(_litigant);

                            //update folder prefix name
                            List<CrmProjectFolder> _stageFolders = _folders.stream().filter(x -> x.getStageid() == _stageid
                                    && x.getRelatedid() != null
                                    && x.getRelatedid().equals(_litigant.getRecid())).collect(Collectors.toList());
                            for (CrmProjectFolder f : _stageFolders) {
                                updateProjectFolderName(f.getRecid(), _litigant.getName());
                            }
                        }
                    }
                }
            } else {
                for (ProjectClient _litigant : _requestLitigants) {
                    String _clientRecid = UUID.randomUUID().toString();
                    insertProjectClientSingle(_projectid, _stageid, _litigantPersonType, _clientRecid, _litigant);

                    //添加对方当事人文件夹
                    String _realFolderName = "";
                    for (CrmProjectBasicFolder _folder : _ligigantStageFolders) {

                        String _theStagePartFolderName = "";
                        if (_folder.getIsReplaceable() && !_newFolderName.isEmpty()) {
                            _theStagePartFolderName = "正式提交给" + _newFolderName + "的材料";
                            _realFolderName = _folderStageName + _theStagePartFolderName;
                        } else {
                            _realFolderName = _folderStageName + _folder.getRecname();
                        }

                        int _innerFolderType = _folder.getInnerfoldertype();
                        boolean _isLawyerFolder = false;
                        String _theFolderRecid = UUID.randomUUID().toString();
                        insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _realFolderName, _ligigantStageFolderType, _clientRecid, _litigant.getName(), _innerFolderType, _isLawyerFolder, userId);
                    }
                }
            }
        }

        if (_litigants != null) {
            for (CrmProjectClient _litigant : _litigants) {
                long _theLitigantCount = _requestLitigants.stream().filter(x -> x.getRecid() != null
                        && x.getRecid().equals(_litigant.getRecid())).count();
                if (_theLitigantCount == 0) {
                    deleteProjectClient(_litigant.getRecid());
                    //delete folder

                    //update folder prefix name
                    List<CrmProjectFolder> _stageFolders = _folders.stream().filter(x -> x.getStageid() == _stageid
                            && x.getRelatedid() != null && x.getRelatedid().equals(_litigant.getRecid())).collect(Collectors.toList());
                    for (CrmProjectFolder f : _stageFolders) {

                        deleteProjectFolder(f.getRecid(), userId);
                    }
                }
            }
        }

        //更新对方当事人文件夹

        //项目基本数据
        List<CrmProjectInfo> _projectInfos = getProjectInfo(_projectid);
        Optional<CrmProjectInfo> _theProjectInfo = _projectInfos.stream().filter(x -> x.getStageid() == _stageid).findFirst();
        if (_theProjectInfo.isPresent()) {
            String _projectInfoRecId = _theProjectInfo.get().getRecid();
            _result = updateProjectInfo(_requestProjectInfo, _projectInfoRecId);
        }

        /** 合议庭和书记员 ***/
        //读取合议庭和数据源
        int _clerkContacType = BaseEnum.ContactType.Clerk.getContactType();
        int _fullCourtContacType = BaseEnum.ContactType.FullCount.getContactType();
        List<CrmProjectContact> _projectContacts = getProjectContact(_projectid, userId);
        List<CrmProjectContact> _projectStageContacts = _projectContacts.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());

        //合议庭,书记员
        List<ProjectContact> _requestFullCourts = _requestProjectInfo.getFullcourt();
        List<ProjectContact> _requestClerks = _requestProjectInfo.getClerk();

        //删除当前阶段的合议庭和数据源
        deleteProjectContact(_projectStageContacts);

        //为当前阶段新增合议庭和数据源
        insertProjectContact(_projectid, _stageid, _fullCourtContacType, _requestFullCourts, userId);
        insertProjectContact(_projectid, _stageid, _clerkContacType, _requestClerks, userId);


        /** 备注和可以查看备注的人 ***/
        //获取备注
        List<CrmProjectRemark> _savedRemarks = getProjectRemark(_projectid, userId);
        List<CrmProjectRemark> _stageSavedRemarks = _savedRemarks.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
        List<ProjectRemark> _requestRemarks = _requestProjectInfo.getRemarks();
        Optional<ProjectRemark> _myRequestRemark = null;
        if (_requestRemarks != null) {
            _myRequestRemark = _requestRemarks.stream().filter(x -> x.getCreatorid() == userId).findFirst();
        }

        Optional<CrmProjectRemark> _mySavedRemark = null;
        if (_stageSavedRemarks != null) {
            _mySavedRemark = _stageSavedRemarks.stream().filter(x -> x.getReccreator() == userId).findFirst();
        }

        Optional<ProjectRemark> _newRequestRemark = null;
        if (_requestRemarks != null) {
            _newRequestRemark = _requestRemarks.stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).findFirst();
        }

        //获取可以看到备注的人
        List<CrmProjectInfoRemarkViewer> _savedViewers = getProjectRemarkViewer(_projectid, userId);
        List<CrmProjectInfoRemarkViewer> _savedStageViewers = _savedViewers.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());

        if (_mySavedRemark != null && _mySavedRemark.isPresent()) {
            //更新
            if (_myRequestRemark != null && _myRequestRemark.isPresent()) {
                ProjectRemark _theRemark = _myRequestRemark.get();
                updateProjectRemark(_theRemark.getRecid(), _theRemark.getContent(), userId);

                //delete viewer
                List<CrmProjectInfoRemarkViewer> _theRemarkSavedViewers = _savedStageViewers.stream().filter(x -> x.getRemarkid().equals(_theRemark.getRecid())).collect(Collectors.toList());
                List<ProjectInfoRemarkViewer> _theRemarkRequestViewers = new ArrayList<>();
                // _theRemark.getViewer();
                for (ProjectInfoRemarkViewer r : _theRemark.getViewer()) {
                    long _theCount = _theRemarkRequestViewers.stream().filter(x -> x.getUserid() == r.getUserid()).count();
                    if (_theCount == 0) {
                        _theRemarkRequestViewers.add(r);
                    }
                }


                if (_theRemarkSavedViewers != null && _theRemarkSavedViewers.size() > 0) {
                    if (_theRemarkRequestViewers != null && _theRemarkRequestViewers.size() > 0) {
                        for (CrmProjectInfoRemarkViewer v : _theRemarkSavedViewers) {
                            long _theViewerCount = _theRemarkRequestViewers.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                            if (_theViewerCount == 0) {
                                deleteProjectRemarkViewer(v.getRecid());
                            }
                        }
                    } else {
                        for (CrmProjectInfoRemarkViewer v : _theRemarkSavedViewers) {
                            deleteProjectRemarkViewer(v.getRecid());
                        }
                    }
                } else {

                    if (_theRemarkRequestViewers != null) {
                        for (ProjectInfoRemarkViewer v : _theRemarkRequestViewers) {
                            insertProjectRemarkViewer(_projectid, _stageid, _theRemark.getRecid(), v.getUserid(), userId);
                        }
                    }
                }

                //add new viewer
                if (_theRemarkRequestViewers != null && _theRemarkRequestViewers.size() > 0) {
                    if (_theRemarkSavedViewers != null && _theRemarkSavedViewers.size() > 0) {
                        for (ProjectInfoRemarkViewer v : _theRemarkRequestViewers) {
                            long _theViewerCount = _theRemarkSavedViewers.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                            if (_theViewerCount == 0) {
                                insertProjectRemarkViewer(_projectid, _stageid, _theRemark.getRecid(), v.getUserid(), userId);
                            }
                        }
                    } else {
                        for (ProjectInfoRemarkViewer v : _theRemarkRequestViewers) {
                            insertProjectRemarkViewer(_projectid, _stageid, _theRemark.getRecid(), v.getUserid(), userId);
                        }
                    }
                } else {

                    if (_theRemarkSavedViewers != null && _theRemarkSavedViewers.size() > 0) {
                        for (CrmProjectInfoRemarkViewer v : _theRemarkSavedViewers) {
                            deleteProjectRemarkViewer(v.getRecid());
                        }
                    }
                }
            }
        } else {
            if (_myRequestRemark != null && _myRequestRemark.isPresent()) {
                //新增
                ProjectRemark _remark = _myRequestRemark.get();
                String _tempRemarkid = _remark.getRecid();
                String _remarkid = UUID.randomUUID().toString();
                if (_tempRemarkid == null || _tempRemarkid.equals("")) {
                    //insert
                    insertProjectRemark(_projectid, _stageid, _remarkid, _remark.getContent(), userId);
                    List<ProjectInfoRemarkViewer> _viewList = new ArrayList<>();//_remark.getViewer();
                    for (ProjectInfoRemarkViewer r : _remark.getViewer()) {
                        long _theCount = _viewList.stream().filter(x -> x.getUserid() == r.getUserid()).count();
                        if (_theCount == 0) {
                            _viewList.add(r);
                        }
                    }

                    if (_viewList != null && _viewList.size() > 0) {
                        insertProjectRemarkViewers(_projectid, _stageid, _remarkid, _viewList, userId);
                    }
                }
            }
        }

        if (_newRequestRemark != null && _newRequestRemark.isPresent()) {
            //新增
            ProjectRemark _remark = _newRequestRemark.get();
            String _remarkid = UUID.randomUUID().toString();

            //insert
            insertProjectRemark(_projectid, _stageid, _remarkid, _remark.getContent(), userId);
            List<ProjectInfoRemarkViewer> _viewList = new ArrayList<>();
            for (ProjectInfoRemarkViewer r : _remark.getViewer()) {
                long _theCount = _viewList.stream().filter(x -> x.getUserid() == r.getUserid()).count();
                if (_theCount == 0) {
                    _viewList.add(r);
                }
            }
            if (_viewList != null && _viewList.size() > 0) {
                insertProjectRemarkViewers(_projectid, _stageid, _remarkid, _viewList, userId);
            }
        }

        if (_result > 0) {
            //send system message
//            try {
            List<String> _messageContent = new ArrayList<>();
            CrmUser _theUser = _commonRepository.getUserInfo(userId);
            String _userName = _theUser.getRealname();

            List<Map<String, String>> contentList = new ArrayList<>();

            //用户姓名编辑了字段名称
            boolean _isClientChanged = false;
            boolean _isLitigantChanged = false;

            //_savedClients
            if (_clients != null && _clients.size() > 0) {
                CrmProjectClient _savedClient = _clients.get(0);
                if (_requestClients != null && _requestClients.size() > 0) {
                    ProjectClient _theRequstClient = _requestClients.get(0);
                    if (!checkNull(_theRequstClient.getTitle()).equals(checkNull(_savedClient.getTitle()))) {
                        _isClientChanged = true;
                    }

                    if (!checkNull(_theRequstClient.getName()).equals(checkNull(_savedClient.getName()))) {
                        _isClientChanged = true;
                    }
                    if (!checkNull(_theRequstClient.getContact()).equals(checkNull(_savedClient.getContact()))) {
                        _isClientChanged = true;
                    }
                    if (!checkNull(_theRequstClient.getPhone()).equals(checkNull(_savedClient.getPhone()))) {
                        _isClientChanged = true;
                    }
                    if (!checkNull(_theRequstClient.getMail()).equals(checkNull(_savedClient.getMail()))) {
                        _isClientChanged = true;
                    }
                }
            }

            //_litigants
            if (_requestLitigants != null && _requestLitigants.size() > 0) {
                if (_litigants != null && _litigants.size() > 0) {
                    for (ProjectClient c : _requestLitigants) {

                        long _theClientCount = _litigants.stream().filter(x -> checkNull(x.getTitle()).equals(checkNull(c.getTitle()))
                                && checkNull(x.getName()).equals(checkNull(c.getName()))
                                && checkNull(x.getContact()).equals(checkNull(c.getContact()))
                                && checkNull(x.getPhone()).equals(checkNull(c.getPhone())) && checkNull(x.getMail()).equals(checkNull(c.getMail()))).count();

                        if (_theClientCount == 0) {
                            _isLitigantChanged = true;
                        }
                    }
                } else {
                    _isLitigantChanged = true;
                }
            } else {
                if (_litigants != null && _litigants.size() > 0) {
                    _isLitigantChanged = true;
                }
            }

            if (_litigants != null && _litigants.size() > 0) {
                if (_requestLitigants != null && _requestLitigants.size() > 0) {
                    for (CrmProjectClient c : _litigants) {

                        long _theClientCount = _litigants.stream().filter(x -> checkNull(x.getTitle()).equals(checkNull(c.getTitle()))
                                && checkNull(x.getName()).equals(checkNull(c.getName()))
                                && checkNull(x.getContact()).equals(checkNull(c.getContact()))
                                && checkNull(x.getPhone()).equals(checkNull(c.getPhone())) && checkNull(x.getMail()).equals(checkNull(c.getMail()))).count();

                        if (_theClientCount == 0) {
                            _isLitigantChanged = true;
                        }
                    }
                } else {
                    _isLitigantChanged = true;
                }
            } else {
                if (_requestLitigants != null && _requestLitigants.size() > 0) {
                    _isLitigantChanged = true;
                }
            }


            if (_isClientChanged) {
                //委托人
                if (_requestClients != null && _requestClients.size() > 0) {
                    String names = _requestClients.stream().map(ProjectClient::getName).collect(Collectors.joining(","));
                    String _content = String.format("%s修改了委托人为：%s", _userName, names);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                } else {
                    String _content = String.format("%s清空了委托人", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }
            }
            //对方当事人
            if (_isLitigantChanged) {
                if (_requestLitigants != null && _requestLitigants.size() > 0) {
                    String names = _requestLitigants.stream().map(ProjectClient::getName).collect(Collectors.joining(","));
                    String _content = String.format("%s修改了对方当事人为：%s", _userName, names);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                } else {
                    String _content = String.format("%s清空了对方当事人", _userName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }
            }

            Optional<CrmProjectInfo> _theStageInfo = _projectInfos.stream().filter(x -> x.getStageid() == _stageid).findFirst();
            if (_theStageInfo.isPresent()) {
                CrmProjectInfo _info = _theStageInfo.get();
                ProjectInfo _requestInfo = _request.getInfo();
                //案由
                if (!checkNull(_info.getCauseofaction()).equals(checkNull(_requestInfo.getCauseofaction()))) {
                    String _fieldShowName = getFieldDisplayName(_fieldsInfos, "causeofaction");
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getCauseofaction());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }
                //审理法院
                if (!checkNull(_info.getCourt()).equals(checkNull(_requestInfo.getCourt()))) {
                    String _fieldShowName = getFieldDisplayName(_fieldsInfos, "court");
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getCourt());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }
                //审理案号
                if (!checkNull(_info.getCasenumber()).equals(checkNull(_requestInfo.getCasenumber()))) {
                    String _fieldShowName = getFieldDisplayName(_fieldsInfos, "casenumber");
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getCasenumber());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                //本诉请求
                if (!checkNull(_info.getClaim()).equals(checkNull(_requestInfo.getClaim()))) {
                    String _fieldShowName = getFieldDisplayName(_fieldsInfos, "claim");
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getClaim());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                //涉嫌罪名
                if (!checkNull(_info.getCrimename()).equals(checkNull(_requestInfo.getCrimename()))) {
                    String _fieldShowName = getFieldDisplayName(_fieldsInfos, "crimename");
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getCrimename());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                //附带民事诉讼请求
                if (!checkNull(_info.getCivilrequest()).equals(checkNull(_requestInfo.getCivilrequest()))) {
                    String _fieldShowName = getFieldDisplayName(_fieldsInfos, "civilrequest");
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getCivilrequest());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }

                SimpleDateFormat _dataFormat = DateUtil.getSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //拘留日期
                if (_info.getDetentiondate() != null && _requestInfo.getDetentiondate() != null) {
                    if (!_dataFormat.format(_info.getDetentiondate()).equals(_requestInfo.getDetentiondate())) {
                        String _fieldShowName = getFieldDisplayName(_fieldsInfos, "detentiondate");
                        String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getDetentiondate());
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }
                }

                //逮捕日期
                if (_info.getArrestdate() != null && _requestInfo.getArrestdate() != null) {
                    if (!_dataFormat.format(_info.getArrestdate()).equals(_requestInfo.getArrestdate())) {
                        String _fieldShowName = getFieldDisplayName(_fieldsInfos, "arrestdate");
                        String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getArrestdate());
                        _messageContent.add(_content);
                        Map<String, String> cMap = new HashMap<>();
                        cMap.put("content", _content);
                        cMap.put("pushType", "1");
                        contentList.add(cMap);
                    }
                }

                //羁押处所
                if (!checkNull(_info.getCustodyplace()).equals(checkNull(_requestInfo.getCustodyplace()))) {
                    String _fieldShowName = getFieldDisplayName(_fieldsInfos, "custodyplace");
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, _requestInfo.getCustodyplace());
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }
            }

            //合议庭,书记员
            boolean _isFullCourtChanged = false;
            List<ProjectContact> _theRequestFullCourt = _request.getInfo().getFullcourt();
            List<CrmProjectContact> _theSavedFullCourt = _projectStageContacts.stream().filter(x -> x.getRectype() == BaseEnum.ContactType.FullCount.getContactType()).collect(Collectors.toList());
            if (_theRequestFullCourt != null && _theRequestFullCourt.size() > 0) {
                if (_theSavedFullCourt != null && _theSavedFullCourt.size() > 0) {
                    for (ProjectContact c : _theRequestFullCourt) {
                        long _theFullCourtCount = _theSavedFullCourt.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                        if (_theFullCourtCount == 0) {
                            _isFullCourtChanged = true;
                        }
                    }
                } else {
                    _isFullCourtChanged = true;
                }
            } else {
                if (_theSavedFullCourt != null && _theSavedFullCourt.size() > 0) {
                    _isFullCourtChanged = true;
                }
            }

            if (_theSavedFullCourt != null && _theSavedFullCourt.size() > 0) {
                if (_theRequestFullCourt != null && _theRequestFullCourt.size() > 0) {

                    for (CrmProjectContact c : _theSavedFullCourt) {
                        long _theFullCourtCount = _theRequestFullCourt.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                        if (_theFullCourtCount == 0) {
                            _isFullCourtChanged = true;
                        }
                    }
                } else {
                    _isFullCourtChanged = true;
                }
            } else {

                if (_theRequestFullCourt != null && _theRequestFullCourt.size() > 0) {
                    _isFullCourtChanged = true;
                }
            }


            boolean _isClerkChanged = false;
            List<ProjectContact> _theRequestClerk = _request.getInfo().getClerk();
            List<CrmProjectContact> _theSavedClerk = _projectStageContacts.stream().filter(x -> x.getRectype() == BaseEnum.ContactType.Clerk.getContactType()).collect(Collectors.toList());
            if (_theRequestClerk != null && _theRequestClerk.size() > 0) {
                if (_theSavedClerk != null && _theSavedClerk.size() > 0) {
                    for (ProjectContact c : _theRequestClerk) {
                        long _theFullCourtCount = _theSavedClerk.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                        if (_theFullCourtCount == 0) {
                            _isClerkChanged = true;
                        }
                    }
                } else {
                    _isClerkChanged = true;
                }
            } else {
                if (_theSavedClerk != null && _theSavedClerk.size() > 0) {
                    _isClerkChanged = true;
                } else {
                    _isClerkChanged = false;
                }
            }

            System.out.println("clerk;" + _theRequestClerk);

            if (_theSavedClerk != null && _theSavedClerk.size() > 0) {
                if (_theRequestClerk != null && _theRequestClerk.size() > 0) {
                    for (CrmProjectContact c : _theSavedClerk) {
                        long _theFullCourtCount = _theRequestClerk.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                        if (_theFullCourtCount == 0) {
                            _isClerkChanged = true;
                        }
                    }
                } else {
                    _isClerkChanged = true;
                }
            } else {

                if (_theRequestClerk != null && _theRequestClerk.size() > 0) {
                    _isClerkChanged = true;
                } else {
                    _isClerkChanged = false;
                }
            }

            if (_isFullCourtChanged) {
                String _fieldShowName = getFieldDisplayName(_fieldsInfos, "fullcourt");
                if (_theRequestFullCourt != null && _theRequestFullCourt.size() > 0) {
                    String names = _theRequestFullCourt.stream().map(ProjectContact::getCombineName).collect(Collectors.joining(","));
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, names);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                } else {
                    String _content = String.format("%s清空了%s", _userName, _fieldShowName);
                    _messageContent.add(_content);
                }
            }

            if (_isClerkChanged) {
                String _fieldShowName = getFieldDisplayName(_fieldsInfos, "clerk");
                if (_theRequestClerk != null && _theRequestClerk.size() > 0) {
                    String names = _theRequestClerk.stream().map(ProjectContact::getCombineName).collect(Collectors.joining(","));
                    String _content = String.format("%s修改了%s为：%s", _userName, _fieldShowName, names);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                } else {
                    String _content = String.format("%s清空了%s", _userName, _fieldShowName);
                    _messageContent.add(_content);
                    Map<String, String> cMap = new HashMap<>();
                    cMap.put("content", _content);
                    cMap.put("pushType", "1");
                    contentList.add(cMap);
                }
            }

            //我的备注
            boolean _isRemarkChanged = false;
            List<CrmProjectRemark> _theStageRemarks = _savedRemarks.stream().filter(x -> x.getStageid() == _stageid && x.getReccreator() == userId).collect(Collectors.toList());
            List<ProjectRemark> _theRequestRemarks = _request.getInfo().getRemarks();
            List<CrmProjectInfoRemarkViewer> _theStageViewer = _savedViewers.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());

            if (_theStageRemarks == null || _theStageRemarks.size() == 0) {
                if (_theRequestRemarks != null && _theRequestRemarks.size() > 0) {
                    for (ProjectRemark r : _theRequestRemarks) {
                        if (r.getContent() != null && !r.getContent().isEmpty()) {
                            _isRemarkChanged = true;
                            break;
                        }
                    }
                }
            } else {
                if (_theRequestRemarks == null || _theRequestRemarks.size() == 0) {
                    _isRemarkChanged = true;
                } else {
                    if (_theStageRemarks.get(0).getContent() != null && !_theStageRemarks.get(0).getContent().equals(_theRequestRemarks.get(0).getContent())) {
                        _isRemarkChanged = true;
                    } else {


                    }
                }
            }


            if (_theRequestRemarks != null && _theRequestRemarks.size() > 0) {
                for (ProjectRemark r : _theRequestRemarks) {
                    if (r.getContent() == null) {
                        continue;
                    }
                    long _theRemarkCount = _theStageRemarks.stream().filter(x -> x.getContent() != null && x.getContent().equals(r.getContent())).count();
                    if (_theRemarkCount == 0) {
                        _isRemarkChanged = true;
                    } else {
                        List<ProjectInfoRemarkViewer> _theViewer = r.getViewer();
                        List<CrmProjectInfoRemarkViewer> _theRemarkViewer = _theStageViewer.stream().filter(x -> x.getRemarkid().equals(r.getRecid())).collect(Collectors.toList());
                        if (_theViewer != null && _theViewer.size() > 0) {
                            if (_theRemarkViewer != null && _theRemarkViewer.size() > 0) {
                                for (ProjectInfoRemarkViewer v : _theViewer) {
                                    long _theViewerCount = _theRemarkViewer.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                                    if (_theViewerCount == 0) {
                                        _isRemarkChanged = true;
                                    }
                                }
                            } else {
                                _isRemarkChanged = true;
                            }
                        } else {
                            if (_theRemarkViewer != null && _theRemarkViewer.size() > 0) {
                                _isRemarkChanged = true;
                            }
                        }

                        if (_theRemarkViewer != null && _theRemarkViewer.size() > 0) {
                            if (_theViewer != null && _theViewer.size() > 0) {
                                for (CrmProjectInfoRemarkViewer v : _theRemarkViewer) {
                                    long _theViewerCount = _theViewer.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                                    if (_theViewerCount == 0) {
                                        _isRemarkChanged = true;
                                    }
                                }
                            } else {
                                _isRemarkChanged = true;
                            }
                        } else {
                            if (_theViewer != null && _theViewer.size() > 0) {
                                _isRemarkChanged = true;
                            }
                        }
                    }
                }
            } else {
                if (_theStageRemarks != null && _theStageRemarks.size() > 0) {
                    _isRemarkChanged = true;
                }
            }


            if (_theStageRemarks != null && _theStageRemarks.size() > 0) {
                if (_theRequestRemarks != null && _theRequestRemarks.size() > 0) {
                    for (CrmProjectRemark r : _theStageRemarks) {
                        long _theRemarkCount = _theRequestRemarks.stream().filter(x -> x.getRecid().equals(r.getRecid())).count();
                        if (_theRemarkCount == 0) {
                            _isRemarkChanged = true;
                        } else {

                            List<CrmProjectInfoRemarkViewer> _theRemarkViewer = _theStageViewer.stream().filter(x -> x.getRemarkid().equals(r.getRecid())).collect(Collectors.toList());
                            Optional<ProjectRemark> _theRequestRemark = _theRequestRemarks.stream().filter(x -> x.getRecid().equals(r.getRecid())).findFirst();
                            if (_theRequestRemark.isPresent()) {
                                List<ProjectInfoRemarkViewer> _theViewer = _theRequestRemark.get().getViewer();
                                if (_theRemarkViewer != null && _theViewer != null) {
                                    for (CrmProjectInfoRemarkViewer v : _theRemarkViewer) {
                                        long _theViewerCount = _theViewer.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                                        if (_theViewerCount == 0) {
                                            _isRemarkChanged = true;
                                        }
                                    }

                                    for (CrmProjectInfoRemarkViewer v : _theRemarkViewer) {
                                        long _theViewerCount = _theViewer.stream().filter(x -> x.getUserid() == v.getUserid()).count();
                                        if (_theViewerCount == 0) {
                                            _isRemarkChanged = true;
                                        }
                                    }
                                }
                                if (_theRemarkViewer == null || _theRemarkViewer.size() == 0) {
                                    if (_theViewer != null && _theViewer.size() > 0) {
                                        _isRemarkChanged = true;
                                    }
                                }

                                if (_theViewer == null || _theViewer.size() == 0) {
                                    if (_theRemarkViewer != null && _theRemarkViewer.size() > 0) {
                                        _isRemarkChanged = true;
                                    }
                                }
                            } else {
                                _isRemarkChanged = true;
                            }
                        }
                    }
                }
            }

                /*
                if (_isRemarkChanged) {
                    String _content = String.format("%s编辑了备注", _userName);
                    _messageContent.add(_content);
                }*/

            List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
            // new Thread(() -> {
            //send system message
           /* for (String _content : _messageContent) {
                List<String> _messageGroupIds = _chatGroups.stream().filter(x -> x.getStageid() == _stageid).map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                if (!_content.isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                    sendIMMessage(_messageGroupIds, _content, userId);
                }
            }*/

            for (Map<String, String> stringMap : contentList) {
                List<String> _messageGroupIds = _chatGroups.stream().filter(x -> x.getStageid() == _stageid).map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                if (!stringMap.get("content").isEmpty() && !stringMap.get("pushType").isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                    sendIMMessage(_messageGroupIds, stringMap.get("content"), userId, Integer.parseInt(stringMap.get("pushType")));
                }
            }

            //  });

//            } catch (Exception ex) {
//                System.out.println("kkkk："+ex.getMessage());
//                ex.printStackTrace();
//            }
        }
        return _result;
    }

    private int updateProjectInfo(ProjectInfo _info, String projectInfoId) throws Exception {
        int _result = 0;

        String _strSql =
                " update crm_project_info " +
                        " set cause_of_action=:cause_of_action," +
                        " court=:court," +
                        " case_number=:case_number," +
                        " claim=:claim," +
                        " remark=:remark, " +
                        " crimename=:crimename," +
                        " civilrequest=:civilrequest, " +
                        " detentiondate=:detentiondate, " +
                        " arrestdate=:arrestdate, " +
                        " custodyplace=:custodyplace " +
                        " where recid=:recid ";


        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", projectInfoId);
        _params.put("cause_of_action", _info.getCauseofaction());
        _params.put("court", _info.getCourt());
        _params.put("case_number", _info.getCasenumber());
        _params.put("claim", _info.getClaim());
        _params.put("remark", "");
        _params.put("crimename", "");
        _params.put("civilrequest", _info.getCivilrequest());

        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String _strDetentiondate = _info.getDetentiondate();
        if (_strDetentiondate != null && !_strDetentiondate.isEmpty()) {
            _params.put("detentiondate", _dataFormat.parse(_strDetentiondate));
        } else {
            _params.put("detentiondate", null);
        }

        String _strArrestdate = _info.getArrestdate();
        if (_strArrestdate != null && !_strArrestdate.isEmpty()) {
            _params.put("arrestdate", _dataFormat.parse(_strArrestdate));
        } else {
            _params.put("arrestdate", null);
        }

        _params.put("custodyplace", _info.getCustodyplace());
        _result = updateEntity(_strSql, _params);
        return _result;
    }

    //新增
    @Transactional
    public int saveProjectStageData(ProjectSaveStageRequest _request, int userId) throws Exception {

        int result = 0;

        try {

            //群组加颜色标记
            String color= RandomColorGenerator.getRandomRGB16();
            //添加项目主数据
            String _projectid = _request.getProjectid();
            int _projectType = _request.getProjecttype();

            CrmUser _theLoginUser = _commonRepository.getUserInfo(userId);


            String _projectName = "";
            List<CrmProject> _projects = getProject(_projectid);
            if (_projects != null && _projects.size() > 0) {
                _projectName = _projects.get(0).getRecname();
            }

            List<CrmProjectStageName> _stageNameList = getProjectStageName(_projectType);
            List<CrmProjectBasicFolder> _basicFolder = getProjectBasicFolder(_projectType);

            int _commonStageFolderType = BaseEnum.ProjectFolderType.Common.getProjectFolderType();
            List<CrmProjectBasicFolder> _commonStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _commonStageFolderType).collect(Collectors.toList());

            //服务端产生的folders
            List<ProjectFolderResponse> _serviceProjectFolders = new ArrayList<>();


            //添加项目文件夹
            String _realFolderName = "";
            String _projectFolderId = UUID.randomUUID().toString();

            List<CrmProjectFolder> _theProjectFolders = getProjectFolder(_projectid, userId);
            List<CrmProjectFolder> _theProjectCommonFolders = _theProjectFolders.stream().filter(x -> x.getFoldertype() == BaseEnum.ProjectFolderType.Common.getProjectFolderType()).collect(Collectors.toList());


/*
          for (CrmProjectBasicFolder _folder : _commonStageFolders) {
                _realFolderName = _folder.getRecname();
                int _innerFolderType = _folder.getInnerfoldertype();
                boolean _isLawyerFolder = false;
                insertProjectFolderBasic(_projectid, 0, _projectFolderId, _realFolderName, _commonStageFolderType, "", "", _innerFolderType, _isLawyerFolder, userId);

                //把生成的文件夹，放进文件夹池子
                ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                _theServiceFolder.setClientid("");
                _theServiceFolder.setFolderid(_projectFolderId);
                _theServiceFolder.setFoldername(_realFolderName);
                _theServiceFolder.setPartanme(_realFolderName);
                _theServiceFolder.setFoldertype(_folder.getRectype());
                _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                _theServiceFolder.setLawyerfolder(false);
                _serviceProjectFolders.add(_theServiceFolder);
            }*/

            for (CrmProjectFolder _folder : _theProjectCommonFolders) {

                //把生成的文件夹，放进文件夹池子
                ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                _theServiceFolder.setClientid("");
                _theServiceFolder.setFolderid(_folder.getRecid());
                _theServiceFolder.setFoldername(_folder.getRecname());
                _theServiceFolder.setPartanme(_folder.getRecname());
                _theServiceFolder.setFoldertype(_folder.getFoldertype());
                _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                _theServiceFolder.setLawyerfolder(false);
                _serviceProjectFolders.add(_theServiceFolder);
            }

            List<ProjectStage> _stages = _request.getStages();
            for (ProjectStage _stage : _stages) {

                int _stageid = _stage.getStageid();
                List<CrmProjectStageName> _currentSageNameList = _stageNameList.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                String _currentStageName = _currentSageNameList.get(0).getStagename();
                String _folderStageName = "(" + _currentStageName + ")";
                _folderStageName = "";

                //虚拟文件夹
                List<ProjectFolderResponse> _folders = _stage.getFolders();

                //服务端产生的阶段
                List<ProjectFolderResponse> _serviceStageFolders = new ArrayList<>();

                //保存项目的阶段
                result = insertProjectStageRelate(_projectid, _stageid, _stage.getStageorder(), userId);

                //委托人文件夹
                int _clientStageFolderType = BaseEnum.ProjectFolderType.Client.getProjectFolderType();
                List<CrmProjectBasicFolder> _clientStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _clientStageFolderType).collect(Collectors.toList());

                //创建分组
                int _chatType = BaseEnum.ChatType.Project.getChatType();
                int _addGroupResult = 0;


                //添加阶段文件夹
                int _theStageFolderType = BaseEnum.ProjectFolderType.Stage.getProjectFolderType();
                List<CrmProjectBasicFolder> _theStageBaseFolders = _basicFolder.stream().filter(x -> x.getRectype() == _theStageFolderType).collect(Collectors.toList());
                for (CrmProjectBasicFolder _folder : _theStageBaseFolders) {

                    String _theFolderRecid = UUID.randomUUID().toString();
                    String _theFolderName = _folderStageName + _folder.getRecname();

                    int _stageFolderType = _folder.getRectype();
                    int _innerfoldertype = _folder.getInnerfoldertype();
                    String _theClientId = "";
                    boolean _isLawyerFolder = false;
                    String _prefixname = "";
                    if (_folder.getFoldertype() == BaseEnum.DefaultFolderType.LawyerFolder.getDefaultFolderType()) {
                        _isLawyerFolder = true;
                        _prefixname = "律师协作团队";
                    }

                    insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _theFolderName, _theStageFolderType, "", _prefixname, _innerfoldertype, _isLawyerFolder, userId);

                    //生成委托人文件夹
                    ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                    _theServiceFolder.setClientid(_theClientId);
                    _theServiceFolder.setFolderid(_theFolderRecid);
                    _theServiceFolder.setFoldername(_theFolderName);
                    _theServiceFolder.setPartanme(_theFolderName);
                    _theServiceFolder.setFoldertype(_stageFolderType);
                    _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                    _theServiceFolder.setLawyerfolder(_isLawyerFolder);
                    _serviceStageFolders.add(_theServiceFolder);

                }

                //添加 委托人
                List<ProjectClientGroup> _clientGroups = new ArrayList<>();
                List<ProjectClient> _clients = _stage.getInfo().getClient();
                int _personType = BaseEnum.PersonType.Client.getPersonType();

                List<ProjectClientFolder> _clientTmp = new ArrayList<>();

                //get special folder
                String _newFolderName = "";
                List<CrmPorjectFolderSpecial> _folderSpecials = getProjectFolderSpecial(_projectType, _stageid);
                if (_folderSpecials != null && _folderSpecials.size() > 0) {
                    CrmPorjectFolderSpecial _special = _folderSpecials.get(0);
                    _newFolderName = _special.getShowname();
                }


                List<String> _clientChatGroups = new ArrayList<>();

                for (ProjectClient _client : _clients) {
                    String _clientRecid = UUID.randomUUID().toString();
                    String _clientName = _client.getName();
                    insertProjectClientSingle(_projectid, _stageid, _personType, _clientRecid, _client);

                    ProjectClientFolder _tmpInfo = new ProjectClientFolder();
                    _tmpInfo.setClientid(_client.getClientid());
                    _tmpInfo.setRecid(_clientRecid);
                    _tmpInfo.setClientname(_clientName);
                    _clientTmp.add(_tmpInfo);

                    //添加委托人团队的委托人组的文件夹
                    for (CrmProjectBasicFolder _folder : _clientStageFolders) {


                        String _theStagePartFolderName = "";
                        if (_folder.getIsReplaceable() && !_newFolderName.isEmpty()) {
                            _theStagePartFolderName = "正式提交给" + _newFolderName + "的材料";
                            _realFolderName = _folderStageName + _theStagePartFolderName;
                        } else {
                            _realFolderName = _folderStageName + _folder.getRecname();
                        }

                        //_realFolderName = _folderStageName + _folder.getRecname();

                        int _innerFolderType = _folder.getInnerfoldertype();
                        boolean _isLawyerFolder = false;
                        String _theFolderRecid = UUID.randomUUID().toString();
                        insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _realFolderName, _clientStageFolderType, _clientRecid, _clientName, _innerFolderType, _isLawyerFolder, userId);

                        //生成委托人文件夹
                        ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                        _theServiceFolder.setClientid(_client.getClientid());
                        _theServiceFolder.setFolderid(_theFolderRecid);
                        _theServiceFolder.setFoldername(_realFolderName);
                        _theServiceFolder.setPartanme(_realFolderName);
                        _theServiceFolder.setFoldertype(_folder.getRectype());
                        _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                        _theServiceFolder.setLawyerfolder(false);
                        _serviceStageFolders.add(_theServiceFolder);
                    }


                    boolean _createIMGroupResult = false;
                    String _clientGroupid = UUID.randomUUID().toString();
                    _clientChatGroups.add(_clientGroupid);

                    //im group name 最长30字节
                    String _groupName = "委托人协作团队";
                    String _imGroupName = "委托人协作团队";
                    String _groupIntroduction = "[" + _currentStageName + "]" + _projectName + "_委托人协作团队";
                    int _clientGroupType = BaseEnum.ChatGroupType.Client.getChatGroupType();

                    _imGroupName = "委协-" + _projectName;
                    if (_imGroupName.length() > 10) {
                        _imGroupName = _imGroupName.substring(0, 10);
                    }

                    _groupIntroduction = _imGroupName;
                    if (_groupIntroduction.length() > 100) {
                        _groupIntroduction = _groupIntroduction.substring(0, 100);
                    }

                    _addGroupResult = insertChatGroup(_clientGroupid, _groupName, _projectid, _stageid, _chatType, _clientGroupType, _clientRecid, _client.getName(), userId,color);
                    if (_addGroupResult > 0) {
                        _createIMGroupResult = _imService.createIMGroup(_clientGroupid, _imGroupName, _groupIntroduction, userId);
                    }

                    if (_createIMGroupResult) {
                        System.out.println("create im group ok 1");
                    }
                    //添加委托人对应的成员
                    List<ProjectMember> _clientMembers = _client.getMembers();
                    if (_clientMembers != null && _clientMembers.size() > 0) {
                        insertProjectMemberBatch(_projectid, _stageid, _clientGroupid, _clientMembers, _clientRecid, userId);

                        //添加IM member
                        List<Integer> _tmpMemberIds = new ArrayList<>();
                        for (ProjectMember _m : _clientMembers) {
                            _tmpMemberIds.add(_m.getUserid());
                        }
                        //添加成员到im group
                        //List<Integer> _lawyerGroupMember = _members.stream().map(x -> x.getUserid()).distinct().collect(Collectors.toList());
                        _imService.addIMGroupMember(_clientGroupid, _tmpMemberIds, userId);
                    }

                    //为添加成员做准备
                    ProjectClientGroup _cg = new ProjectClientGroup();
                    _cg.setRecid(_clientRecid);
                    _cg.setClientid(_client.getClientid());
                    _cg.setGroupid(_clientGroupid);
                    _clientGroups.add(_cg);
                }


                //添加 对方当事人
                _personType = BaseEnum.PersonType.litigant.getPersonType();
                List<ProjectClient> _litigants = _stage.getInfo().getLitigant();
                int _ligigantStageFolderType = BaseEnum.ProjectFolderType.Litigant.getProjectFolderType();
                List<CrmProjectBasicFolder> _ligigantStageFolders = _basicFolder.stream().filter(x -> x.getRectype() == _ligigantStageFolderType).collect(Collectors.toList());

                for (ProjectClient _client : _litigants) {

                    String _clientRecid = UUID.randomUUID().toString();
                    insertProjectClientSingle(_projectid, _stageid, _personType, _clientRecid, _client);

                    ProjectClientFolder _tmpInfo = new ProjectClientFolder();
                    _tmpInfo.setClientid(_client.getClientid());
                    _tmpInfo.setRecid(_clientRecid);
                    _tmpInfo.setClientname(_client.getName());
                    _clientTmp.add(_tmpInfo);

                    //添加对方当事人文件夹
                    for (CrmProjectBasicFolder _folder : _ligigantStageFolders) {

                        String _theStagePartFolderName = "";
                        if (_folder.getIsReplaceable() && !_newFolderName.isEmpty()) {
                            _theStagePartFolderName = "正式提交给" + _newFolderName + "的材料";
                            _realFolderName = _folderStageName + _theStagePartFolderName;
                        } else {
                            _realFolderName = _folderStageName + _folder.getRecname();
                        }


                        //   _realFolderName = _folderStageName + _folder.getRecname();
                        int _innerFolderType = _folder.getInnerfoldertype();
                        boolean _isLawyerFolder = false;
                        String _theFolderRecid = UUID.randomUUID().toString();
                        insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _realFolderName, _ligigantStageFolderType, _clientRecid, _client.getName(), _innerFolderType, _isLawyerFolder, userId);

                        //生成委托人文件夹
                        ProjectFolderResponse _theServiceFolder = new ProjectFolderResponse();
                        _theServiceFolder.setClientid(_client.getClientid());
                        _theServiceFolder.setFolderid(_theFolderRecid);
                        _theServiceFolder.setFoldername(_realFolderName);
                        _theServiceFolder.setPartanme(_realFolderName);
                        _theServiceFolder.setFoldertype(_folder.getRectype());
                        _theServiceFolder.setInnerfoldertype(_folder.getInnerfoldertype());
                        _theServiceFolder.setLawyerfolder(false);
                        _serviceStageFolders.add(_theServiceFolder);
                    }
                }

                //添加项目基础数据
                insertProjectInfo(_projectid, _stageid, _stage);

                //添加备注
                List<ProjectRemark> _remarks = _stage.getInfo().getRemarks();
                for (ProjectRemark _remark : _remarks) {

                    String _recid = UUID.randomUUID().toString();
                    insertProjectRemark(_projectid, _stageid, _recid, _remark.getContent(), userId);

                    //添加可以看到备注的人
                    List<ProjectInfoRemarkViewer> _viewers = _remark.getViewer();
                    insertProjectRemarkViewers(_projectid, _stageid, _recid, _viewers, userId);
                }
                //合议庭张三
                int _contactType = BaseEnum.ContactType.FullCount.getContactType();
                List<ProjectContact> _fullCount = _stage.getInfo().getFullcourt();
                insertProjectContact(_projectid, _stageid, _contactType, _fullCount, userId);

                //书记员王五
                _contactType = BaseEnum.ContactType.Clerk.getContactType();
                List<ProjectContact> _clerks = _stage.getInfo().getClerk();
                insertProjectContact(_projectid, _stageid, _contactType, _clerks, userId);


                //把自定义文件夹，保存到数据库
                //直接使用客户端传来的folderid
                // todo:需要使用来自客户端的clientid么
                int _userDefineFolderType = BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType();
                List<ProjectFolderResponse> _userDefinefolders = _folders.stream().filter(x -> x.getFoldertype() == _userDefineFolderType).collect(Collectors.toList());
                if (_userDefinefolders != null && _userDefinefolders.size() > 0) {
                    for (ProjectFolderResponse _folder : _userDefinefolders) {
                        String _theFolderRecid = _folder.getFolderid();
                        String _theRealFolderName = _folder.getFoldername();
                        int _innerFolderType = _folder.getInnerfoldertype();
                        boolean _isLawyerFolder = !_folder.isLawyerfolder();
                        String _prefixName = "";
                        String _relatedId = "";

                        _innerFolderType = getNextInnerFolderType(_projectid);
                        insertProjectFolderBasic(_projectid, _stageid, _theFolderRecid, _theRealFolderName, _userDefineFolderType, _relatedId, _prefixName, _innerFolderType, _isLawyerFolder, userId);
                    }
                }

                //根据文件夹，编辑，然后写文件入数据
                List<ProjectFileFolder> _fileFolders = _stage.getFiles();
                if (_fileFolders != null && _fileFolders.size() > 0) {
                    for (ProjectFileFolder _folder : _fileFolders) {
                        int _theFolderType = _folder.getFoldertype();
                        if (_theFolderType == _commonStageFolderType) {

                            //从服务端文件夹中找到对应的文件夹
                            String _theFolerid = "";
                            Optional<ProjectFolderResponse> _theServiceFolder = _serviceProjectFolders.stream().filter(x -> x.getFoldertype() == _folder.getFoldertype()
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                            if (_theServiceFolder.isPresent()) {
                                ProjectFolderResponse _serviceFolder = _theServiceFolder.get();
                                _theFolerid = _serviceFolder.getFolderid();
                            }

                            List<ProjectFile> _theFiles = _folder.getItems();
                            if (_theFiles != null && _theFiles.size() > 0) {
                                for (ProjectFile _f : _theFiles) {
                                    String _fileRecid = UUID.randomUUID().toString();
                                    _f.setFolderid(_theFolerid);
                                    //把文件写入数据库
                                    insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                                }
                            }
                        } else if (_theFolderType == _theStageFolderType) {

                            //从服务端文件夹中找到对应的文件夹
                            String _theFolerid = "";
                            Optional<ProjectFolderResponse> _theServiceFolder = _serviceStageFolders.stream().filter(x -> x.getFoldertype() == _folder.getFoldertype()
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                            if (_theServiceFolder.isPresent()) {
                                ProjectFolderResponse _serviceFolder = _theServiceFolder.get();
                                _theFolerid = _serviceFolder.getFolderid();
                            }

                            List<ProjectFile> _theFiles = _folder.getItems();
                            if (_theFiles != null && _theFiles.size() > 0) {
                                for (ProjectFile _f : _theFiles) {
                                    String _fileRecid = UUID.randomUUID().toString();
                                    _f.setFolderid(_theFolerid);
                                    //把文件写入数据库
                                    insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                                }
                            }

                        } else if (_theFolderType == _userDefineFolderType) {

                            //把文件写入数据库
                            List<ProjectFile> _theFiles = _folder.getItems();
                            if (_theFiles != null && _theFiles.size() > 0) {
                                for (ProjectFile _f : _theFiles) {
                                    String _fileRecid = UUID.randomUUID().toString();
                                    _f.setFolderid(_folder.getFolderid());
                                    insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                                }
                            }

                        } else {

                            //找到文件夹对应的委托人或者对方当事人
                            //  Optional<ProjectFolderResponse> _requestFolder = _folders.stream().filter(x -> x.getFolderid().equals(_folder.getFolderid())).findFirst();
                            //  if (_requestFolder.isPresent()) {
                            //  ProjectFolderResponse _theRequestFolder = _requestFolder.get();
                            //  String _theClientId = _theRequestFolder.getClientid();

                            //找到服务端对应的文件夹
                            String _theFolerid = "";
                            String _theClientId = _folder.getClientid();
                            Optional<ProjectFolderResponse> _theServiceFolder = _serviceStageFolders.stream().filter(x -> x.getClientid().equals(_theClientId)
                                    && x.getFoldertype() == _folder.getFoldertype()
                                    && x.getInnerfoldertype() == _folder.getInnerfoldertype()).findFirst();
                            if (_theServiceFolder.isPresent()) {
                                ProjectFolderResponse _serviceFolder = _theServiceFolder.get();
                                _theFolerid = _serviceFolder.getFolderid();
                            }

                            //把文件写入数据库
                            List<ProjectFile> _theFiles = _folder.getItems();
                            if (_theFiles != null && _theFiles.size() > 0) {
                                for (ProjectFile _f : _theFiles) {
                                    String _fileRecid = UUID.randomUUID().toString();
                                    _f.setFolderid(_theFolerid);
                                    insertProjectFileBasic(_projectid, _stageid, _fileRecid, _f, userId);
                                }
                            }
                            // }


                        }
                    }
                }


                //添加项目任务
                List<ProjectTask> _tasks = _stage.getTasks();
                if (_tasks != null) {
                    insertProjectTasks(_projectid, _stageid, _tasks, userId);
                }

                //添加律师协作团队聊天组
                boolean _createIMGroupResult = false;
                int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
                // String _clientGroupid = UUID.randomUUID().toString();

                _addGroupResult = 0;
                String _lawyerGroupid = UUID.randomUUID().toString();
                //String _groupName = _projectName + "律师协作团队";
                String _groupName = "律师协作团队";
                String _imGroupName = "律师协作团队";
                String _groupIntroduction = "[" + _currentStageName + "]" + _projectName + "_律师协作团队";
                int _lawyerGroupType = BaseEnum.ChatGroupType.Lawyer.getChatGroupType();

                _imGroupName = "律协-" + _projectName;
                if (_imGroupName.length() > 10) {
                    _imGroupName = _imGroupName.substring(0, 10);
                }

                _groupIntroduction = _imGroupName;
                if (_groupIntroduction.length() > 100) {
                    _groupIntroduction = _groupIntroduction.substring(0, 100);
                }

                _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, _projectid, _stageid, _chatType, _lawyerGroupType, "", "", userId,color);
                if (_addGroupResult > 0) {
                    _createIMGroupResult = _imService.createIMGroup(_lawyerGroupid, _imGroupName, _groupIntroduction, userId);
                }
                if (_createIMGroupResult) {
                    System.out.println("create im group ok 2");
                }

                //添加律师协作团队成员
                List<ProjectMember> _members = _stage.getMembers();
                insertProjectMember(_projectid, _stageid, _lawyerGroupid, _members, userId);

                //添加成员到im group
                List<Integer> _lawyerGroupMember = _members.stream().map(x -> x.getUserid()).distinct().collect(Collectors.toList());
                _imService.addIMGroupMember(_lawyerGroupid, _lawyerGroupMember, userId);

                //send add stage message
                if (result > 0) {
                    List<String> groupids = new ArrayList<>();
                    groupids.add(_lawyerGroupid);
                    groupids.addAll(_clientChatGroups);

                    String _content = String.format("%s添加了阶段：%s", _theLoginUser.getRealname(), _currentStageName);
                    sendIMMessage(groupids, _content, userId, 0);
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }

    @Transactional
    public int renameProjectFile(ProjectRenameFileRequest _request, int userid) {

        int _result = 0;
        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        String _filerecid = _request.getFilerecid();
        String _newFileName = _request.getNewfilename();
        String _sourceFileName = _request.getSourcefilename();

        String _fileSuffix = "";
        List<CrmProjectFile> _files = getProjectFiles(_projectid, userid);
        if (_files != null && _files.size() > 0) {
            Optional<CrmProjectFile> _theFile = _files.stream().filter(x -> x.getStageid() == _stageid && x.getRecid().equals(_filerecid)).findFirst();
            if (_theFile.isPresent()) {
                String _oldFileName = _theFile.get().getFilename();
                _fileSuffix = FilenameUtils.getExtension(_oldFileName);
            }
        }

        if (_fileSuffix.isEmpty()) {
            _newFileName = _newFileName + "." + _fileSuffix;
        }

        String _strSql = " update crm_project_file " +
                " set filename=:filename,sourcefilename=:sourcefilename " +
                " where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", _filerecid);
        _params.put("filename", _newFileName);
        _params.put("sourcefilename", _sourceFileName);
        _result = updateEntity(_strSql, _params);
        if (_result > 0) {

            //new Thread(() -> {

            //send system message
            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            String _folderName = _files.stream().filter(x -> x.getStageid() == _stageid && x.getRecid().equals(_filerecid)).findFirst().get().getFoldername();
            //用户姓名上传了/删除了/重命名了文件；
            String _content = String.format("%s重命名了文件：%s 文件夹：%s",
                    _theUser.getRealname(),
                    _request.getNewfilename(),
                    _folderName);

            boolean _isClientVisible = getIsClientVisible(_projectid, _filerecid, userid);
            SendIMGroupMessage(_projectid, _stageid, _content, _isClientVisible, userid);

/*
                List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
                List<String> _messageGroupIds = _chatGroups.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                if (!_content.isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                    sendIMMessage(_messageGroupIds, _content, userid);
                }*/
            //}).start();
        }
        return _result;
    }

    @Transactional
    public int deleteProjectFile(ProjectDeleteFileRequest _request, int userid) {

        int _result = 0;
        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        String _filerecid = _request.getFilerecid();


        boolean _isClientVisible = false;
        List<CrmProjectFile> _files = getProjectFiles(_projectid, userid);
        String _fileName = "";
        String _folderName = "";
        if (_files != null && _files.size() > 0) {
            Optional<CrmProjectFile> _theFile = _files.stream().filter(x -> x.getRecid().equals(_filerecid)).findFirst();
            if (_theFile.isPresent()) {
                _fileName = _theFile.get().getFilename();
                _folderName = _theFile.get().getFoldername();
                String _folderId = _theFile.get().getFolderid();
                List<CrmProjectFolder> _folders = getProjectFolder(_projectid, userid);
                if (_folders != null && _folders.size() > 0) {
                    Optional<CrmProjectFolder> _theFolder = _folders.stream().filter(x -> x.getRecid().equals(_folderId)).findFirst();
                    if (_theFolder.isPresent()) {
                        _isClientVisible = !_theFolder.get().islawyerfolder();
                    }
                }
            }
        }

        String _strSql = " update crm_project_file set recstatus=0 where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", _filerecid);
        _result = updateEntity(_strSql, _params);


        if (_result > 0) {

            //send system message
            CrmUser _theUser = _commonRepository.getUserInfo(userid);

            //用户姓名上传了/删除了/重命名了文件；
            String _content = String.format("%s删除了文件：%s 文件夹：%s", _theUser.getRealname(), _fileName, _folderName);

            SendIMGroupMessage(_projectid, _stageid, _content, _isClientVisible, userid);

         /*   List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
            List<String> _messageGroupIds = _chatGroups.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
            if (!_content.isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                sendIMMessage(_messageGroupIds, _content, userid);
            }*/

        }
        return _result;
    }


    @Transactional
    public int addProjectFile(ProjectAddFileRequest _request, int userid) {

        int _result = 0;

        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        List<ProjectFileFolder> _folders = _request.getFiles();
        if (_folders != null && _folders.size() > 0) {
            for (ProjectFileFolder f : _folders) {
                _result = insertProjectFile(_projectid, _stageid, f.getItems(), userid);


            }
        }

        if (_result > 0) {
            new Thread(() -> {
                List<ProjectFileFolder> _thefolders = _request.getFiles();
                for (ProjectFileFolder _folder : _thefolders) {
                    String _folderId = _folder.getFolderid();
                    List<ProjectFile> _files = _folder.getItems();
                    for (ProjectFile f : _files) {
                        //send system message
                        CrmUser _theUser = _commonRepository.getUserInfo(userid);

                        //用户姓名上传了/删除了/重命名了文件；
                        String _content = String.format("%s上传了文件:%s", _theUser.getRealname(), f.getFilename());
                        //String _content = String.format("%s上传了文件:%s到文件夹%s", _theUser.getRealname(), f.getFilename(), _folder.getFoldername());
                        boolean _isClientVisible = false;
                        _isClientVisible = getIsClientVisibleByFolderId(_projectid, _folderId, userid);

                        String _extraData = f.getUploadfileid() + "." + f.getExtension();
                        JSONObject extJsonObject = new JSONObject();
                        extJsonObject.put("fileid", f.getFileid());
                        extJsonObject.put("uploadfileid", f.getUploadfileid());
                        extJsonObject.put("filename", f.getFilename());
                        extJsonObject.put("ext", f.getExtension());
                        SendIMGroupMessageFile(_projectid, _stageid, _content, _isClientVisible, _extraData, extJsonObject, userid);
                    }
                }

                /*
                List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
                List<String> _messageGroupIds = _chatGroups.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                if (!_content.isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                    sendIMMessage(_messageGroupIds, _content, userid);
                }*/

            }).start();
        }
        return _result;
    }
    @Transactional
    public int addProjectFile2(ProjectAddFileRequest _request, int userid) {

        int _result = 0;

        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        List<ProjectFileFolder> _folders = _request.getFiles();
        if (_folders != null && _folders.size() > 0) {
            for (ProjectFileFolder f : _folders) {
                _result = insertProjectFile(_projectid, _stageid, f.getItems(), userid);


            }
        }

        if (_result > 0) {
            new Thread(() -> {
                List<ProjectFileFolder> _thefolders = _request.getFiles();
                for (ProjectFileFolder _folder : _thefolders) {
                    String _folderId = _folder.getFolderid();
                    List<ProjectFile> _files = _folder.getItems();
                    for (ProjectFile f : _files) {
                        //send system message
                        CrmUser _theUser = _commonRepository.getUserInfo(userid);

                        //用户姓名上传了/删除了/重命名了文件；
                        String _content = String.format("%s上传了文件:%s", _theUser.getRealname(), f.getFilename());
                        //String _content = String.format("%s上传了文件:%s到文件夹%s", _theUser.getRealname(), f.getFilename(), _folder.getFoldername());
                        boolean _isClientVisible = false;
                        _isClientVisible = getIsClientVisibleByFolderId(_projectid, _folderId, userid);

                        String _extraData = f.getUploadfileid() + "." + f.getExtension();
                        JSONObject extJsonObject = new JSONObject();
                        extJsonObject.put("fileid", f.getFileid());
                        extJsonObject.put("uploadfileid", f.getUploadfileid());
                        extJsonObject.put("filename", f.getFilename());
                        extJsonObject.put("ext", f.getExtension());
                        SendIMGroupMessageFile2(_projectid, _stageid, _content, _isClientVisible, _extraData, extJsonObject, userid);
                    }
                }

                /*
                List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
                List<String> _messageGroupIds = _chatGroups.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                if (!_content.isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                    sendIMMessage(_messageGroupIds, _content, userid);
                }*/

            }).start();
        }
        return _result;
    }

    public String getProjectGroupId(String projectid, int stageid, int grouptype) {

        String _groupid = "";
        String _clientChatGroupId = "";
        String _lawyerChatGroupId = "";
        List<CrmChatGroupPart> _chatGroups = _commonRepository.getProjectChatGroup(projectid);
        List<CrmChatGroupPart> _stageChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == stageid).collect(Collectors.toList());
        if (_chatGroups != null) {
            Optional<CrmChatGroupPart> _clientChatGroup = _stageChatGroups.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();
            if (_clientChatGroup.isPresent()) {
                _clientChatGroupId = _clientChatGroup.get().getGroupid();
            }
            Optional<CrmChatGroupPart> _lawyerChatGroup = _stageChatGroups.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();
            if (_lawyerChatGroup.isPresent()) {
                _lawyerChatGroupId = _lawyerChatGroup.get().getGroupid();
            }
        }

        if (grouptype == BaseEnum.GroupType.Client.getGroupType()) {
            _groupid = _clientChatGroupId;

        } else if (grouptype == BaseEnum.GroupType.Lawyer.getGroupType()) {
            _groupid = _lawyerChatGroupId;
        }
        return _groupid;
    }


    public int setProjectHost(ProjectSetHostRequest _request, int userid) {

        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        int _groupType = _request.getGrouptype();
        int _innerGroupType = _request.getInnergrouptype();
        int _memberid = _request.getMemberid();

        int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
        int _lawyerGroupType = BaseEnum.GroupType.Lawyer.getGroupType();
        int _clientInnerGroupType = BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType();
        int _lawyerInnerGroupType = BaseEnum.InnerGroupType.LawyerGroup.getInnerGroupType();
        List<CrmProjectMember> _theMembers = null;

        List<CrmProjectMember> _members = getProjectMember(_projectid, userid);
        if (_members != null) {
            List<CrmProjectMember> _stageMembers = _members.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            if (_stageMembers != null) {
                if (_groupType == _clientGroupType && _innerGroupType == _clientInnerGroupType) {
                    _theMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == _groupType && x.getInnergrouptype() == _innerGroupType).collect(Collectors.toList());
                    if (_theMembers != null) {
                        setMemberRole(_theMembers, _memberid);
                    }
                } else {

                    //set lawyer
                    _theMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == _lawyerGroupType).collect(Collectors.toList());
                    if (_theMembers != null) {
                        setMemberRole(_theMembers, _memberid);
                    }

                    //set client
                    _theMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == _clientGroupType && x.getInnergrouptype() == _lawyerInnerGroupType).collect(Collectors.toList());
                    if (_theMembers != null) {
                        setMemberRole(_theMembers, _memberid);
                    }
                }

            }

            new Thread(() -> {
                List<CrmProjectStage> _stages = getProjectStage(_request.getStageid());
                String _stageName = "";
                if (_stages != null && _stages.size() > 0) {
                    _stageName = _stages.get(0).getStagename();
                }

                //send system message
                //管理员变更为用户姓名
                CrmUser _theUser = _commonRepository.getUserInfo(_memberid);
                String _content = "";
                if (_groupType == _clientGroupType) {
                    if (_innerGroupType == _clientInnerGroupType) {
                        _content = String.format("%s委托人组主办人变更为%s", _stageName, _theUser.getRealname());
                    } else {
                        //律师代理组
                        _content = String.format("%s主办人变更为%s", _stageName, _theUser.getRealname());
                    }
                } else {
                    //律师协助团队
                    _content = String.format("%s主办人变更为%s", _stageName, _theUser.getRealname());
                }

                List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
                List<String> _messageGroupIds = _chatGroups.stream().filter(x -> x.getStageid() == _stageid).map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                if (!_content.isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                    sendIMMessage(_messageGroupIds, _content, userid, 1);
                }

            }).start();
        }
        return 1;
    }


    public void setMemberRole(List<CrmProjectMember> _theMembers, int _memberid) {

        Optional<CrmProjectMember> _member = _theMembers.stream().filter(x -> x.getUserid() == _memberid).findFirst();
        Optional<CrmProjectMember> _memberHost = _theMembers.stream().filter(x -> x.ishost()).findFirst();
        //cancel as host
        if (_memberHost.isPresent()) {
            String _hostMemberId = _memberHost.get().getRecid();
            setProjectMemberHost(_hostMemberId, false);
        }
        //set as host
        if (_member.isPresent()) {
            String _memberRecId = _member.get().getRecid();
            setProjectMemberHost(_memberRecId, true);
        }

    }


    public int setProjectMemberHost(String recid, boolean isHost) {
        int _result = 0;
        String _strSql = " update crm_project_member set ishost=:ishost where recid=:recid";
        Map<String, Object> _params = new HashMap<>();
        _params.put("ishost", isHost);
        _params.put("recid", recid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }


    public int setProjectManager(ProjectSetManagerRequest _request, int userid) {

        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        int _groupType = _request.getGrouptype();
        int _innerGroupType = _request.getInnergrouptype();
        int _memberid = _request.getMemberid();

        int _clientGroupType = BaseEnum.GroupType.Client.getGroupType();
        int _lawyerGroupType = BaseEnum.GroupType.Lawyer.getGroupType();
        int _clientInnerGroupType = BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType();
        int _lawyerInnerGroupType = BaseEnum.InnerGroupType.LawyerGroup.getInnerGroupType();
        List<CrmProjectMember> _theMembers = null;

        List<CrmProjectMember> _members = getProjectMember(_projectid, userid);
        if (_members != null) {
            List<CrmProjectMember> _stageMembers = _members.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            if (_stageMembers != null) {
                if (_groupType == _clientGroupType && _innerGroupType == _clientInnerGroupType) {
                    _theMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == _clientGroupType && x.getInnergrouptype() == _clientInnerGroupType).collect(Collectors.toList());
                    setManagerRole(_theMembers, _memberid);
                } else {
                    _theMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == _lawyerGroupType).collect(Collectors.toList());
                    setManagerRole(_theMembers, _memberid);

                    _theMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == _clientGroupType && x.getInnergrouptype() == _lawyerInnerGroupType).collect(Collectors.toList());
                    setManagerRole(_theMembers, _memberid);
                }
            }

            new Thread(() -> {
                List<CrmProjectStage> _stages = getProjectStage(_request.getStageid());
                String _stageName = "";
                if (_stages != null && _stages.size() > 0) {
                    _stageName = _stages.get(0).getStagename();
                }

                //send system message
                //管理员变更为用户姓名
                CrmUser _theUser = _commonRepository.getUserInfo(_memberid);
                String _content = "";
                if (_groupType == _clientGroupType) {
                    if (_innerGroupType == _clientInnerGroupType) {
                        _content = String.format("%s委托人组管理员变更为%s", _stageName, _theUser.getRealname());
                    } else {
                        _content = String.format("%s律师代理组管理员变更为%s", _stageName, _theUser.getRealname());
                    }
                } else {
                    _content = String.format("%s律师协助团队管理员变更为%s", _stageName, _theUser.getRealname());
                }

                List<CrmChatGroupPart> _chatGroups = getProjectChatGroup(_projectid);
                List<String> _messageGroupIds = _chatGroups.stream().filter(x -> x.getStageid() == _stageid).map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                if (!_content.isEmpty() && _messageGroupIds != null && _messageGroupIds.size() > 0) {
                    sendIMMessage(_messageGroupIds, _content, userid, 1);
                }

            }).start();


        }
        return 1;
    }


    private void setManagerRole(List<CrmProjectMember> _theMembers, int _memberid) {

        Optional<CrmProjectMember> _member = _theMembers.stream().filter(x -> x.getUserid() == _memberid).findFirst();
        Optional<CrmProjectMember> _memberManager = _theMembers.stream().filter(x -> x.getIsmanager()).findFirst();

        //cancel as host
        if (_memberManager.isPresent()) {
            String _hostMemberId = _memberManager.get().getRecid();
            setProjectMemberManager(_hostMemberId, false);
        }

        //set as host
        if (_member.isPresent()) {
            String _memberRecId = _member.get().getRecid();
            setProjectMemberManager(_memberRecId, true);
        }
    }


    public int setProjectMemberManager(String recid, boolean isManager) {
        int _result = 0;
        String _strSql = " update crm_project_member set ismanager=:ismanager where recid=:recid";
        Map<String, Object> _params = new HashMap<>();
        _params.put("ismanager", isManager);
        _params.put("recid", recid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }


    public List<CrmProjectFile> getProjectFileById(String recid) {
        String _strSql = " select * from crm_project_file where recid=:recid";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        return getEntitys(_strSql, _params, CrmProjectFile.class);
    }


    public List<CrmProjectFolder> getProjectFolderById(String recid) {
        String _strSql = " select recid,recname,stageid,foldertype,relatedid,reccreator,prefixname,innerfoldertype,islawyerfolder " +
                " from crm_project_folder" +
                "  where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        return getEntitys(_strSql, _params, CrmProjectFolder.class);
    }

    public boolean getIsClientVisible(String _projectid, String _filerecid, int userid) {

        boolean _isClientVisible = false;
        List<CrmProjectFile> _files = getProjectFiles(_projectid, userid);
        if (_files != null && _files.size() > 0) {
            Optional<CrmProjectFile> _theFile = _files.stream().filter(x -> x.getRecid().equals(_filerecid)).findFirst();
            if (_theFile.isPresent()) {
                String _folderId = _theFile.get().getFolderid();
                List<CrmProjectFolder> _folders = getProjectFolder(_projectid, userid);
                if (_folders != null && _folders.size() > 0) {
                    Optional<CrmProjectFolder> _theFolder = _folders.stream().filter(x -> x.getRecid().equals(_folderId)).findFirst();
                    if (_theFolder.isPresent()) {
                        _isClientVisible = !_theFolder.get().islawyerfolder();
                    }
                }
            }
        }
        return _isClientVisible;
    }

    public boolean getIsClientVisibleByFolderId(String _projectid, String _folderId, int userid) {

        boolean _isClientVisible = false;
        List<CrmProjectFolder> _folders = getProjectFolder(_projectid, userid);
        if (_folders != null && _folders.size() > 0) {
            Optional<CrmProjectFolder> _theFolder = _folders.stream().filter(x -> x.getRecid().equals(_folderId)).findFirst();
            if (_theFolder.isPresent()) {
                _isClientVisible = !_theFolder.get().islawyerfolder();
            }
        }
        return _isClientVisible;
    }


    public List<CrmProjectInfoField> getProjectInfoFields(int projectType, int stageid) {
        List<CrmProjectInfoField> _list = new ArrayList<>();
        try {
            if (projectType == BaseEnum.ProjectDefineType.MSXZ.getProjectDefineType())
                stageid = 24;
            else if (projectType == BaseEnum.ProjectDefineType.XS.getProjectDefineType())
                stageid = 39;
            else if (projectType == BaseEnum.ProjectDefineType.FLGW.getProjectDefineType())
                stageid = 48;
            else
                stageid = 49;
            String _strSql = " select recid, fieldname,displayname,url " +
                    " from   crm_project_info_field " +
                    " where recstatus=1 " +
                    "  and  projecttype=:projecttype " +
                    "  and stageid=:stageid " +
                    " order by recorder asc ";

            Map<String, Object> _params = new HashMap<>();
            _params.put("projecttype", projectType);
            _params.put("stageid", stageid);
            _list = getEntitys(_strSql, _params, CrmProjectInfoField.class);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _list;
    }


    public int deleteTask(String taskid) {
        int _result = 0;
        String _strSql = " update crm_task set recstatus=0 where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", taskid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }


    public List<CrmProjectStage> getProjectStage(int stageid) {

        String _strSql =
                "select s.recid,s.recname,s.datastageid,s.stagetype,0 as recorder,false as iscomplete " +
                        " from crm_project_stage s " +
                        " where s.recid=:recid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", stageid);
        List<CrmProjectStage> _stageList = getEntitys(_strSql, _params, CrmProjectStage.class);
        return _stageList;


    }


    public List<ProjectFileFolder> getProjectFiles(GetProjectFileRequest _request, int userid) {

        String _projectid = _request.getProjectid();
        int _stateid = _request.getStageid();

        List<CrmProjectMember> _memberList = getProjectMember(_projectid, userid);
        List<CrmProjectMember> _stageMembers = _memberList.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());

        List<CrmProjectFolder> _folders = getProjectFolder(_projectid, userid);
        List<CrmProjectFolder> _projectFolders = _folders.stream().filter(x -> x.getFoldertype() == BaseEnum.ProjectFolderType.Common.getProjectFolderType()).collect(Collectors.toList());

        List<CrmProjectFile> _fileList = getProjectFiles(_projectid, userid);
        List<CrmProjectFile> _stageFiles = _fileList.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());

        //文件资料
        List<ProjectFile> _fileReponse = new ArrayList<>();
        for (CrmProjectFile _file : _stageFiles) {
            ProjectFile file = toProjectFile(_file);
            _fileReponse.add(file);

        }

        //判断登陆用户是否是律师协作团队成员
        boolean _userInLaywerMember = false;
        List<CrmProjectMember> _lawerMemberTmp = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()
                && x.getUserid() == userid).collect(Collectors.toList());
        if (_lawerMemberTmp != null && _lawerMemberTmp.size() > 0) {
            _userInLaywerMember = true;
        }

        //获取拥有权限的文件夹
        List<String> _folderids = new ArrayList<>();
        if (!_userInLaywerMember) {
            List<CrmProjectFolder> _stageFolders = _folders.stream().filter(x -> x.getStageid() == _stateid).collect(Collectors.toList());
            for (CrmProjectFolder _f : _stageFolders) {
                if (_f.getFoldertype() == BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType() && _f.islawyerfolder()) {
                    continue;
                } else if (_f.getFoldertype() == BaseEnum.ProjectFolderType.Stage.getProjectFolderType() && _f.islawyerfolder()) {
                    continue;
                } else {
                    _folderids.add(_f.getRecid());
                }
            }
            //添加项目的文件夹id
            for (CrmProjectFolder f : _projectFolders) {
                _folderids.add(f.getRecid());
            }
        } else {
            _folderids = _fileReponse.stream().map(ProjectFile::getFolderid).distinct().collect(Collectors.toList());
        }

        //把文件归属给文件夹
        List<ProjectFileFolder> _files = new ArrayList<>();
        List<String> _theFileFolders = _fileReponse.stream().map(ProjectFile::getFolderid).collect(Collectors.toList());
        _theFileFolders = _theFileFolders.stream().distinct().collect(Collectors.toList());

        if (_theFileFolders != null && _theFileFolders.size() > 0) {
            for (String _folderid : _theFileFolders) {
                if (_folderids.contains(_folderid)) {
                    List<CrmProjectFolder> _theTmpFolders = _folders.stream().filter(x -> x.getRecid().equals(_folderid)).collect(Collectors.toList());
                    String _folderName = "";
                    CrmProjectFolder _currentFolder = null;
                    boolean _isClientFolder = false;
                    boolean _isUserDefineFolder = false;
                    if (_theTmpFolders != null && _theTmpFolders.size() > 0) {
                        _currentFolder = _theTmpFolders.get(0);
                        _folderName = _currentFolder.getPrefixname() + _currentFolder.getRecname();
                        _isClientFolder = !_currentFolder.islawyerfolder();
                        if (_currentFolder.getFoldertype() == BaseEnum.ProjectFolderType.UserDefine.getProjectFolderType()) {
                            _isUserDefineFolder = true;
                        }
                    }

                    //如果有文件，就添加到列表中来
                    List<ProjectFile> _tmpItems = _fileReponse.stream().filter(x ->x.getFolderid()!=null&&x.getFolderid().equals(_folderid)).collect(Collectors.toList());
                    if (_tmpItems != null && _tmpItems.size() > 0) {
                        ProjectFileFolder _f = new ProjectFileFolder();
                        _f.setFolderid(_folderid);
                        _f.setFoldername(_folderName);
                        _f.setIsclientfolder(_isClientFolder);
                        _f.setIsuserdefinefolder(_isUserDefineFolder);

                        if (_currentFolder != null) {
                            _f.setClientid(_currentFolder.getRelatedid());
                            _f.setFoldertype(_currentFolder.getFoldertype());
                            _f.setInnerfoldertype(_currentFolder.getInnerfoldertype());
                        } else {
                            _f.setClientid("");
                            _f.setFoldertype(0);
                            _f.setInnerfoldertype(0);
                        }
                        _f.setItems(_tmpItems);
                        _files.add(_f);
                    }
                }
            }
        }
        return _files;
    }

    //获取分页数据
    public List<CrmProject> getCrmProjectPage(GetTaskPageItemsRequest _request, int userid) {

        String _searchKey = _request.getSearchkey();
        int _pageIndex = _request.getPageindex();
        int _pageSize = _request.getPagesize();
        int _offset = _pageSize * (_pageIndex - 1);

        String _strSql = " select recid,recname,current_stage,projecttype,projectstatus " +
                "  from crm_project" +
                " where recstatus=1 " +
                " and recid in (select projectid from crm_project_member where recstatus=1 and userid=:userid) ";


        String _where_name_sql = " and recname like" + "'%" + _searchKey + "%'";
        String _orderby_sql = " order by createtime desc limit " + _pageSize + " offset " + _offset;

        if (!_searchKey.isEmpty()) {
            _strSql += _where_name_sql;
        }
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);
        List<CrmProject> _list = getEntitys(_strSql, _params, CrmProject.class);
        return _list;
    }


    public PageSummary getProjectPageCount(GetTaskPageItemsRequest _request, int userid) {
        int _pageIndex = _request.getPageindex();
        int _pageSize = _request.getPagesize();
        String _searchKey = _request.getSearchkey();

        int _pageCount = 0;
        int _total = 0;

        String _strCountSql = " select count(1) " +
                "  from crm_project" +
                " where recstatus=1 " +
                " and recid in (select projectid from crm_project_member where recstatus=1 and userid=:userid) ";

        String _where_name_sql = " and recname like" + "'%" + _searchKey + "%'";
        if (!_searchKey.isEmpty()) {
            _strCountSql += _where_name_sql;
        }

        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);
        _total = getEntityCount(_strCountSql, _params);

        if ((_total % _pageSize) > 0) {
            _pageCount = (_total / _pageSize) + 1;
        } else {
            _pageCount = _total / _pageSize;
        }

        PageSummary _pageSummary = new PageSummary();
        _pageSummary.setPage(_pageCount);
        _pageSummary.setTotal(_total);

        return _pageSummary;
    }

    public List<ProjectList> getProjectInfoPage(List<CrmProject> _list, int userid) {

        List<ProjectList> _projects = new ArrayList<>();
        try {
            for (CrmProject _p : _list) {
                String _projectId = _p.getRecid();

                List<CrmProjectStage> _stageList = getProjectStageList(_projectId);

                //委托人和对方当事人
                List<CrmProjectClient> _clientList = getProjectClient(_projectId);
                List<CrmProjectClient> _clients = _clientList.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.Client.getPersonType()).collect(Collectors.toList());

                //团队成员
                List<CrmProjectMember> _memberList = getProjectMember(_projectId, userid);

                List<ProjectListStage> _responseStages = new ArrayList<>();
                for (CrmProjectStage _stage : _stageList) {
                    ProjectListStage _listStage = new ProjectListStage();
                    _listStage.setStagename(_stage.getStagename());
                    _listStage.setStageid(_stage.getStageid());

                    List<String> _clientNames = new ArrayList<>();
                    List<CrmProjectClient> _tmpClients = _clients.stream().filter(x -> x.getStageid() == _stage.getStageid()).collect(Collectors.toList());
                    for (CrmProjectClient c : _tmpClients) {
                        _clientNames.add(c.getName());
                    }
                    _listStage.setClients(_clientNames);

                    //判断是否是主办人
                    boolean _isHost = false;
                    List<CrmProjectMember> _tmpMembers = _memberList.stream().filter(x -> x.getStageid() == _stage.getStageid()).collect(Collectors.toList());
                    if (_tmpMembers != null && _tmpMembers.size() > 0) {
                        List<CrmProjectMember> _tmpMembers2 = _tmpMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()
                                && x.getUserid() == userid && x.ishost()).collect(Collectors.toList());
                        if (_tmpMembers2 != null && _tmpMembers2.size() > 0) {
                            _isHost = true;
                        }
                    }
                    _listStage.setIshost(_isHost);
                    _responseStages.add(_listStage);
                }
                ProjectList _tmpProjectList = toProjectList(_p);
                _tmpProjectList.setStages(_responseStages);
                _tmpProjectList.setProjecttype(_p.getProjecttype());
                if (_p.getProjectstatus() == BaseEnum.ProjectStatusType.Complete.getProjectStatusType()) {
                    _tmpProjectList.setIscomplete(true);
                } else {
                    _tmpProjectList.setIscomplete(false);
                }

                _projects.add(_tmpProjectList);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }

        return _projects;
    }


    public List<CrmProject> getUnCompletedProjects(String searchkey, int userid) {

        String _strSql = " select recid,recname,current_stage,projecttype,projectstatus " +
                "  from crm_project t" +
                " where t.recstatus=1 " +
                " and t.projectstatus!=1 " +
                " and t.recid in (select projectid from crm_project_member where recstatus=1 and userid=:userid) " +
                " and  exists(  select 1 from crm_project_stage_relate  where projectid=t.recid and stagestatus=1)";

        String _where_name_sql = " and recname like" + "'%" + searchkey + "%'";
        String _orderby_sql = " order by createtime desc  ";

        if (!searchkey.isEmpty()) {
            _strSql += _where_name_sql;
        }
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);
        List<CrmProject> _list = getEntitys(_strSql, _params, CrmProject.class);
        return _list;
    }


    public List<ProjectList> getProjectInfoPage2(List<CrmProject> _list, int userid) {

        List<ProjectList> _projects = new ArrayList<>();
        try {
            for (CrmProject _p : _list) {
                String _projectId = _p.getRecid();

                List<CrmProjectStage2> _stageList = getProjectStageList2(_projectId, "task");

                //委托人和对方当事人
                List<CrmProjectClient> _clientList = getProjectClient(_projectId);
                List<CrmProjectClient> _clients = _clientList.stream().filter(x -> x.getPersontype() == BaseEnum.PersonType.Client.getPersonType()).collect(Collectors.toList());

                //团队成员
                List<CrmProjectMember> _memberList = getProjectMember(_projectId, userid);

                List<ProjectListStage> _responseStages = new ArrayList<>();
                for (CrmProjectStage2 _stage : _stageList) {
                    ProjectListStage _listStage = new ProjectListStage();
                    _listStage.setStagename(_stage.getStagename());
                    _listStage.setStageid(_stage.getStageid());

                    List<String> _clientNames = new ArrayList<>();
                    List<CrmProjectClient> _tmpClients = _clients.stream().filter(x -> x.getStageid() == _stage.getStageid()).collect(Collectors.toList());
                    for (CrmProjectClient c : _tmpClients) {
                        _clientNames.add(c.getName());
                    }
                    _listStage.setClients(_clientNames);

                    //判断是否是主办人
                    boolean _isHost = false;
                    List<CrmProjectMember> _tmpMembers = _memberList.stream().filter(x -> x.getStageid() == _stage.getStageid()).collect(Collectors.toList());
                    if (_tmpMembers != null && _tmpMembers.size() > 0) {
                        List<CrmProjectMember> _tmpMembers2 = _tmpMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()
                                && x.getUserid() == userid && x.ishost()).collect(Collectors.toList());
                        if (_tmpMembers2 != null && _tmpMembers2.size() > 0) {
                            _isHost = true;
                        }
                    }
                    _listStage.setIshost(_isHost);
                    _responseStages.add(_listStage);
                }


                ProjectList _tmpProjectList = toProjectList(_p);
                _tmpProjectList.setStages(_responseStages);
                _tmpProjectList.setProjecttype(_p.getProjecttype());
                if (_p.getProjectstatus() == BaseEnum.ProjectStatusType.Complete.getProjectStatusType()) {
                    _tmpProjectList.setIscomplete(true);
                } else {
                    _tmpProjectList.setIscomplete(false);
                }

                _projects.add(_tmpProjectList);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }

        return _projects;
    }


    public int setFileViewed(ProjectViewdFileRequest _request, int userid) {

       /* String _fileId = _request.getFileid();
        int _result = 0;
        String _strSql = " update crm_project_file set isviewed=1 where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", _fileId);
        _result = updateEntity(_strSql, _params);
        return _result;*/

        String _fileid = _request.getFileid();
        String _strSql = " update crm_task_file set isviewed=true where recid=:recid ";

        int _theCount = _commonRepository.getFileViewedCount(_fileid, userid);
        if (_theCount == 0) {

            _strSql = " insert into crm_view_file_history(recid,filerecid,viewerid,reccreator)values(:recid,:filerecid,:viewerid,:reccreator)";
            Map<String, Object> _params = new HashMap<>();

            String _recId = UUID.randomUUID().toString();
            _params.put("recid", _recId);
            _params.put("filerecid", _fileid);
            _params.put("viewerid", userid);
            _params.put("reccreator", userid);

            return updateEntity(_strSql, _params);
        } else {
            return 1;
        }

    }


    public int setFolderLawyerVisible(ProjectSetFolderVisibleRequest _request, int userid) {

        String folderid = _request.getFolderid();
        boolean islawyerfolder = _request.islawyervisible();

        int _result = 0;
        String _strSql = " update crm_project_folder " +
                " set islawyerfolder=:islawyerfolder " +
                " where recid=:recid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", folderid);
        _params.put("islawyerfolder", islawyerfolder);
        _result = updateEntity(_strSql, _params);
        return _result;
    }


    public List<CrmProject> getProjectListForTask(String searchkey, int userid) {

        String _strSql = " select recid,recname,current_stage,projecttype,projectstatus " +
                "  from crm_project t" +
                " where t.recstatus=1 " +
                " and  t.recid in (select projectid from crm_project_member where recstatus=1 and userid=:userid) " +
                " and exists (select 1 from crm_project_stage_relate where projectid= t.recid and stagestatus=1)";

        String _where_name_sql = " and recname like" + "'%" + searchkey + "%'";
        String _orderby_sql = " order by createtime desc  ";

        if (!searchkey.isEmpty()) {
            _strSql += _where_name_sql;
        }
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);
        List<CrmProject> _list = getEntitys(_strSql, _params, CrmProject.class);
        return _list;
    }


    public GetPermissionResponse getProjectPermissions(GetPermissionRequest _requst, int userid) {

        String _projectId = _requst.getProjectid();
        int _stageId = _requst.getStageid();
        int _theUserId = _requst.getUserid();
        List<CrmProjectMember> _members = getProjectMember(_projectId, userid);
        List<CrmProjectMember> _stageMembers = _members.stream().filter(x -> x.getStageid() == _stageId).collect(Collectors.toList());
        List<CrmProjectMember> _stageLawyerMembers = _stageMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()).collect(Collectors.toList());

        boolean _isInLawyerMember = false;
        boolean _isLawyerManaer = false;
        boolean _isLawyerHost = false;
        if (_stageLawyerMembers != null && _stageLawyerMembers.size() > 0) {
            long _theCount = _stageLawyerMembers.stream().filter(x -> x.getUserid() == _theUserId).count();
            if (_theCount > 0) {
                _isInLawyerMember = true;
            }
            _theCount = _stageLawyerMembers.stream().filter(x -> x.getUserid() == _theUserId && x.ishost()).count();
            if (_theCount > 0) {
                _isLawyerHost = true;
            }

            _theCount = _stageLawyerMembers.stream().filter(x -> x.getUserid() == _theUserId && x.getIsmanager()).count();
            if (_theCount > 0) {
                _isLawyerManaer = true;
            }


        }

        GetPermissionResponse _response = new GetPermissionResponse();
        _response.setIslawyerhost(_isLawyerHost);
        _response.setIslawyermanager(_isLawyerManaer);
        _response.setIslawyermember(_isInLawyerMember);

        return _response;


    }


    public List<CrmProjectInfoExp> getProjectInfoExp(String projectId, int stageId, int userid) {
        String _strSql = " with ptTemp as(\n" +
                "\tselect * from crm_project_type\n" +
                "),\n" +
                "psTemp as(\n" +
                "\tselect * from crm_project_stage \n" +
                "),\n" +
                "piTemp as( \n" +
                " select * from crm_project_info pi\n" +
                "),\n" +
                "chatTemp as(\n" +
                "\tselect * from crm_chat_group\n" +
                ")\n" +
                "\n" +
                "select \n" +
                "ptTemp.recname as projecttypename, /*项目类型*/\n" +
                "p.recid as projectid,\n" +
                "p.recname as projectname, /*项目名称*/\n" +
                "psTemp.recid as stageid,\n" +
                "psTemp.recname as stagename, /*项目阶段*/\n" +
                "chatTemp.recid as groupid,\n" +
                "chatTemp.recname as groupname\n" +
                "\n" +
                "from crm_project p\n" +
                "left join ptTemp on p.projecttype = ptTemp.recid\n" +
                "left join piTemp on piTemp.projectid = p.recid\n" +
                "left join psTemp on psTemp.recid = piTemp.stageid\n" +
                "left join chatTemp on chatTemp.objectid = p.recid and chatTemp.stageid = piTemp.stageid\n" +
                "where p.recstatus = 1 and p.recid=:projectId and piTemp.stageid =:stageId";

        String _orderby_sql = " order by chatTemp.grouptype asc, p.createtime desc  ";
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectId", projectId);
        _params.put("stageId", stageId);
        List<CrmProjectInfoExp> _list = getEntitys(_strSql, _params, CrmProjectInfoExp.class);
        return _list;
    }

    public List<CrmProjectMemberExp> getProjectMemberExp(String projectId, int stageId, String groupId, int userid) {
        String _strSql = " select pm.recid, pm.userid, u.realname as username, pm.ismanager, pm.ishost, pm.grouptype, pm.innergrouptype from crm_project_member pm\n" +
                "left join crm_user u on pm.userid = u.id\n" +
                "where pm.recstatus = 1 and pm.projectid=:projectId and pm.stageid =:stageId\n" +
                "and pm.groupid =:groupId";

        String _orderby_sql = " order by pm.ishost desc, pm.ismanager desc, pm.createtime desc  ";
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectId", projectId);
        _params.put("stageId", stageId);
        _params.put("groupId", groupId);
        List<CrmProjectMemberExp> _list = getEntitys(_strSql, _params, CrmProjectMemberExp.class);
        return _list;
    }

    public List<CrmProjectLogExp> getProjectLogExp(String groupId, int userid) {
        String _strSql = " select m.recid, m.groupid, g.recname as groupname, m.msgseq, m.msgtime, m.content, u.realname as username,'' as sendtime from crm_chat_callback_message m\n" +
                "left join crm_user u on m.sender = u.id\n" +
                "left join crm_chat_group g on g.recid = m.groupid\n" +
                "where m.content is not null and m.content <> '' and m.groupid =:groupId ";

        String _orderby_sql = " order by m.msgtime desc  ";
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("groupId", groupId);
        List<CrmProjectLogExp> _list = getEntitys(_strSql, _params, CrmProjectLogExp.class);
        return _list;
    }

    public List<CrmProjectFileExp> getProjectFileExp(String projectId, int stageId, int userid) {
        String _strSql = " select pf.recid, pf.uploadfileid, pf.filename, folder.recname as foldername\n" +
                "from crm_project_file pf\n" +
                "inner join crm_project_folder folder on pf.folderid = folder.recid and pf.stageid = folder.stageid\n" +
                "where pf.recstatus = 1 and pf.projectid=:projectId and pf.stageid =:stageId";

        String _orderby_sql = " order by pf.createtime desc  ";
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectId", projectId);
        _params.put("stageId", stageId);
        List<CrmProjectFileExp> _list = getEntitys(_strSql, _params, CrmProjectFileExp.class);
        return _list;
    }

    public List<CrmProjectStageInfoExp> getProjectStageInfoExp(String projectId, int stageId, int userid) {
        String _strSql = " select client.recid, client.persontype,projectid, title, name, contact, phone, mail, rectype\n" +
                "from crm_project_client client\n" +
                "where client.projectid =:projectId and client.stageid =:stageId\n" +
                "and client.recstatus = 1 ";

        String _orderby_sql = " order by client.createtime desc  ";
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectId", projectId);
        _params.put("stageId", stageId);
        List<CrmProjectStageInfoExp> _list = getEntitys(_strSql, _params, CrmProjectStageInfoExp.class);
        return _list;
    }

    public List<CrmProjectContactExp> getProjectContactExp(String projectId, int stageId, int userid) {
        String _strSql = " select recid, name, phone, rectype\n" +
                "from crm_project_contact contact\n" +
                "where contact.projectid =:projectId and contact.stageid =:stageId\n" +
                "and contact.recstatus = 1 ";

        String _orderby_sql = " order by contact.createtime desc  ";
        _strSql += _orderby_sql;

        Map<String, Object> _params = new HashMap<>();
        _params.put("projectId", projectId);
        _params.put("stageId", stageId);
        List<CrmProjectContactExp> _list = getEntitys(_strSql, _params, CrmProjectContactExp.class);
        return _list;
    }
    //end of class
}




